8.2 Accessing Variables Outside a Function


8.2 Accessing Variables Outside a Function

You want to access a global variable from inside the scope of a function.

Technique

Use 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"; } 

Comments

In 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;     } } 


PHP Developer's Cookbook
PHP Developers Cookbook (2nd Edition)
ISBN: 0672323257
EAN: 2147483647
Year: 2000
Pages: 351

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net