Introduction
$GLOBALS is an associative array of references to all globalle defined variables. Names of variables form keys and their contents are values of associative array.
$GLOBALS example
This example shows $GLOBALS array containing name and contents of global variables
Example
<?php $var1="Hello"; $var2=100; $var3=array(1,2,3); echo $GLOBALS["var1"] . "\n"; echo $GLOBALS["var2"] . "\n"; echo implode($GLOBALS["var3"]) . "\n"; ?>
Output
This will produce following result. −
Hello 100 123
In following example, $var1 is defined in global namespace as well as a local variable inside function. Global variable is extracted from $GLOBALS array;
Example
<?php function myfunction(){ $var1="Hello PHP"; echo "var1 in global namespace:" . $GLOBALS['var1']. "\n"; echo "var1 as local variable :". $var1; } $var1="Hello World"; myfunction(); ?>
Output
This will produce following result. −
var1 in global namespace:Hello World var1 as local variable :Hello PHP