PHP $GLOBALS
PHP keeps an array called $GLOBALS that holds references to every global variable in your script.
It is one of the superglobals, the built-in variables you can reach from anywhere, whatever the scope.
Global Variables
A global variable is one that every scope can reach.
Making one takes no special step: anything you create in the outermost scope of a script is global automatically, and any scope may use it.
Functions are the catch. Before a function can use a global variable, it must do one of two things: declare the variable with the global keyword, or reach it through $GLOBALS.
Refer to Global Variable With $GLOBALS
Here a function reads the global $x through $GLOBALS:
Output: PHP script
<?php
$x = 75;
function myfunction() {
echo $GLOBALS['x'];
}
myfunction();
?>
Without $GLOBALS
Leave out $GLOBALS and the function can't see the global variable, so PHP gives you nothing, or an error:
Output: PHP script
<?php
$x = 75;
function myfunction() {
echo $x;
}
myfunction();
?>
Use the global Keyword
The global keyword is the other option. Declare the variable with it inside the function, and from then on you can use the plain name:
Output: PHP script
<?php
$x = 75;
function myfunction() {
global $x;
echo $x;
}
myfunction();
?>
Create Global Variables
Whether you write $GLOBALS or not, a variable created at the outermost level of a script ends up global.
Outer Scope Variables Are Global
This variable is created at the top level and then read twice, through $GLOBALS and directly by name. Both give the same value:
Output: PHP script
<?php
$x = 100;
echo $GLOBALS['x'];
echo $x;
?>
Create Global Variable Inside a Function
Normally a variable created in a function exists only within that function. Writing to $GLOBALS changes that, because the new entry becomes a global variable the rest of the script can use, as $z does here:
Output: PHP script
<?php
$x = 10;
$y = 20;
function result() {
$GLOBALS['z'] = $GLOBALS['x'] + $GLOBALS['y'];
}
result();
echo $z;
?>