4.5 Working with PHP Globals


You want to see all the different global variables existing in the script.

Technique

Print the entire $GLOBALS array using PHP's functions for processing associative arrays:

 <?php reset($GLOBALS); while (list($key, $var) = each($GLOBALS)) {     print "$key => $var\ n<br>\ n"; } ?> 

Comments

The example uses PHP's list() and each() functions to iteratively process the $GLOBALS array. It then prints the keys ( names of the variables stored in the $GLOBALS array) and their corresponding values.

The $GLOBALS array contains all variables not defined within the scope of a function as well as PHP's built-in arrays and variables, which are discussed in the next recipe. Here is a quick example to better explain the $GLOBALS array:

 <?php $foo = "fly"; function run() {     $bar = "honey"; } ?> 

In this example, $foo would be stored in the $GLOBALS array (because it is defined outside the scope of the function) and $bar would not be included in the $GLOBALS array ( $bar is defined within the scope of function run() ).

To access a variable that is not declared within the current function, you must do one of two things: either access it through the $GLOBALS array or declare the variable as the global variable. Still using the preceding example, if we want to access $foo in the function set_bar() , we have to do one of the following two things:

Example 1: Access $foo directly through the $GLOBALS array:

 <?php $foo = "fly"; function run() {     print $GLOBALS["foo"]; } ?> 

Example 2: Tell the function that we are referring to the global $foo :

 <?php $foo = "fly"; function run() {     global $foo;     print $foo; } ?> 

Both of these functions print the value of $foo ”they are two different ways to do the same thing. There is, however, one difference: In example 2, $foo now refers to the global variable $foo throughout the function; in example 1, if you then accessed plain $foo , it would refer to the $foo that is local to the function. Another notable point is that in example 2, the variable $foo declared inside the function as global is actually a reference to the $GLOBALS['foo'] value.

Note also that you never need to declare the $GLOBALS array as global inside a function because it resides in the active symbol, not in the global symbol table. (However, it is a reference to the global symbol table, so it is present in the global symbol table.)



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