8.2 Accessing Variables Outside a Function
TechniqueUse the global declaration to say that the variable you are referring to is a global variable: $foo = "noobar"; function foobar () { global $foo; print $foo; // prints noobar } Or access the variable directly via the $GLOBALS array: $foo = "noobar"; function foobar() { $foo = 5; // The local foo print "The global variable is $GLOBALS[foo], "; print "The local variable is $foo"; } CommentsIn PHP, the $GLOBALS array contains all variables that are of global scope, or all variables not within the scope of a function or class. (For more information on the $GLOBALS array, see recipe 14.5.) If you are working within a class, you might want to instead declare your global (not really, but it is global within the class) variable as a var . Then you can access it through the $this variable (for more on OOP, see Chapter 9, "Classes"); consider the following: class foo { var $name = "noobar"; function foobar () { print $this->name; } } |