Saturday, March 24, 2007

The global keyword

$a = 1;
$b = 2;
$GLOBALS['c'] = 3;
echo $c, "<br>";
$d = 4;

function Sum()
global $a, $b;

$b = $a + $b + $GLOBALS['c'] + $GLOBALS['d'];

echo $b;

The above script will output "3", "10". By declaring $a and $b global within the function, all references to either variable will refer to the global version. There is no limit to the number of global variables that can be manipulated by a function.

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

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.

No comments :