PHP $GLOBALS
The $GLOBALS superglobal is an array that contains references to all global variables of the script.
PHP superglobals are built-in variables that are always accessible in all scopes!
Global Variables
Global variables are variables that can be accessed from any scope.
Variables of the outer most scope are automatically global variables, and can be used by any scope.
However, to use a global variable inside a function you have to either define them as global with the global keyword, or refer to them by using the $GLOBALS syntax.
Example
Refer to the global variable $x inside a function:
$x = 75;
function myfunction() {
echo $GLOBALS['x'];
}
myfunction()
This is different from other programming languages where global variables are available without referring to them as global.
Example
In PHP you get nothing (or an error) when referring to a global variable without the $GLOBALS syntax:
$x = 75;
function myfunction() {
echo $x;
}
myfunction()
You can also refer to global variables inside functions by defining them as global with the global keyword.
Example
Define $x as global inside a function:
$x = 75;
function myfunction() {
global $x;
echo $x;
}
myfunction()
Create Global Variables
Variables created in the outer most scope are global variables either if they are created using the $GLOBALS syntax or not.
Example
$x = 100;
echo $GLOBALS['x'];
echo $x;
Variables created inside a function only belongs to that function, but you can create global variables inside a function by using the $GLOBALS syntax.
Example
Create a global variable (z) inside a function, and use it outside of the function:
$x = 10;
$y = 20;
function result() {
$GLOBALS['z'] = $GLOBALS['x'] + $GLOBALS['y'];
}
result();
echo $z;