PHP: Using $GLOBALS instead of global

This entry is part 11 of 54 in the series PHP Tutorial

A second way to access variables from the global scope is to use the special PHP-defined $GLOBALS array.

The previous example can be rewritten as:

$a = 1;
$b = 2;

function Sum()
    $GLOBALS['b'] = $GLOBALS['a'] + $GLOBALS['b'];

echo $b;

The $GLOBALS array is an associative array with the name of the global variable being the key and the contents of that variable being the value of the array element.

Notice how $GLOBALS exists in any scope, this is because $GLOBALS is a superglobal.

Series Navigation<< PHP: Variable with global keyword
PHP: Superglobals >>