Recipe 6.11. Accessing a Global Variable Inside a Function


6.11.1. Problem

You need to access a global variable inside a function.

6.11.2. Solution

Bring the global variable into local scope with the global keyword:

function eat_fruit($fruit) {    global $chew_count;    for ($i = $chew_count; $i > 0; $i--) {        ...    } }

Or reference it directly in $GLOBALS:

function eat_fruit($fruit) {    for ($i = $GLOBALS['chew_count']; $i > 0; $i--) {        ...    } }

6.11.3. Discussion

If you use a number of global variables inside a function, the global keyword may make the syntax of the function easier to understand, especially if the global variables are interpolated in strings.

You can use the global keyword to bring multiple global variables into local scope by specifying the variables as a comma-separated list:

global $age,$gender,shoe_size;

You can also specify the names of global variables using variable variables:

$which_var = 'age'; global $$which_var; // refers to the global variable $age

However, if you call unset( ) on a variable brought into local scope using the global keyword, the variable is unset only within the function. To unset the variable in the global scope, you must call unset( ) on the element of the $GLOBALS array:

$food =  'pizza'; $drink = 'beer'; function party() {     global $food, $drink;     unset($food);             // eat pizza     unset($GLOBALS['drink']); // drink beer } print "$food: $drink\n"; party(); print "$food: $drink\n"; pizza: beer pizza:

You can see that $food stayed the same, while $drink was unset. Declaring a variable global inside a function is similar to assigning a reference of the global variable to the local one:

$food = &GLOBALS['food'];

6.11.4. See Also

Documentation on variable scope at http://www.php.net/variables.scope and variable references at http://www.php.net/language.references.




PHP Cookbook, 2nd Edition
PHP Cookbook: Solutions and Examples for PHP Programmers
ISBN: 0596101015
EAN: 2147483647
Year: 2006
Pages: 445

Similar book on Amazon

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