In PHP, both global and $GLOBALS are used to access global variables. The global keyword is a language construct, while $GLOBALS is a superglobal variable. Both can be used to manipulate global variables, but there are some differences in their usage.
When using the global keyword, the variable needs to be declared again inside each function to bring the global variable into the function's scope. For example:
$global_var = 10;
function test_global() {
global $global_var;
echo $global_var;
}
test_global(); // Outputs 10
When using the $GLOBALS superglobal variable, the global variable can be accessed directly inside the function without needing to declare the scope. For example:
$global_var = 10;
function test_global() {
echo $GLOBALS['global_var'];
}
test_global(); // Outputs 10
As shown above, using $GLOBALS is simpler.
The scope of a variable declared with the global keyword is limited to the current function. However, when using the $GLOBALS superglobal, the variable can be accessed throughout the entire script.
$global_var = 10;
function test_global() {
global $global_var;
echo $global_var;
}
function test_globals() {
echo $GLOBALS['global_var'];
}
test_global(); // Outputs 10
test_globals(); // Outputs 10
As seen above, the global keyword can only access the global variable within the function, whereas $GLOBALS can access it throughout the entire script.
Although both global and $GLOBALS can be used to access global variables, it is recommended to use the $GLOBALS superglobal in practical development for the following reasons:
Using $GLOBALS allows you to avoid repeatedly declaring the global keyword inside functions, making the code cleaner and simpler.
In some highly secured environments, the global keyword may be disabled, but $GLOBALS is not subject to this restriction.
By using $GLOBALS, global variables can be accessed throughout the entire script, making it easier for other parts of the code to reference them.
Although both global and $GLOBALS can be used to access global variables, they have some differences. To keep the code simple and improve compatibility, developers should prioritize using the $GLOBALS superglobal variable.