Accessing a Global Variable Inside a Function






Accessing a Global Variable Inside a Function

Problem

You need to access a global variable inside a function.

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--) {
       ...
   }
}

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'];

See Also

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



 Python   SQL   Java   php   Perl 
 game development   web development   internet   *nix   graphics   hardware 
 telecommunications   C++ 
 Flash   Active Directory   Windows