This shows you the differences between two versions of the page.

Link to this comparison view

computers:php_variable_and_function_scope [2015/03/24 05:42] (current)
Line 1: Line 1:
 +====== PHP Variable & Function Scope ======
 +Nested functions can tell you a bit about how this works. ​ It seems child functions are available to global scope after they have been seen once, but variables are unreachable. ​ Classes work similar, interestingly child_functions are able to reach objects instantiated at global level (after global $object;), even if class declaration is inside parent function. ​ Moral is to use classes ​ to accomplish complicated tasks, and always instantiate at global level, then you can reach what you need when you need it.
 +<code php>
 +//Nested function tests scope
 +$var1 = "This is \$var1 OUTSIDE parent function <br />";​
 +function parent_function() {
 +    echo "Now inside parent <br />";​
 +    $var1 = "This is \$var1 INSIDE parent function <br />";​
 +    $var2 = "This is \$var2 INSIDE parent function <br />";​
 +    class vegatable{
 +        var $color = "​Green";​
 +        var $forChild = "Hello Child";​
 +    }
 +    function child_function() {
 +        echo "now inside child <br />";​
 +        //global $var1; //Calls var1 outside nectedFunct
 +        echo $var1; //​doesn'​t work without global;
 +        // even if we comment out $var1 outside parent function.
 +        // global $var1 doesn'​t reach the one inside parent function.
 +        echo $var2; //​doesn'​t work; Can't seem to reach parent variables.
 +        //We are able to reach callses in parent
 +        // $carrot = new vegatable();​ //works,
 +        // without above new veg declaration,​ below doesn'​t work
 +        // eventhough child is called agains after new veg created.
 +        echo $carrot->​color . "<​br />";​ //Outputs Green only when instantiated inside this function;s
 +        global $carrot;
 +        echo $carrot->​forChild . "<​br />";​ //works only after carrot instantiated at global scope;
 +    }
 +    echo "Now calling child<br />";​
 +    //​child_function(); ​   //works
 +// child_function();​ //causes fatal error: call to undefined function;
 +//$carrot = new vegatable(); ​ //causes fatal error: call to undefined function;
 +parent_function(); ​ //works;
 +child_function();​ //Now works;
 +$carrot = new vegatable();​ //Now works;
 +$carrot->​color = "​Orange";​
 +echo $carrot->​color . "<​br />"; ​   //Outputs Orange;
 +child_function();​ //Outputs "​Green"​ when carrot = new veg inside child, otherwise doesn'​t work;