Current Location: Home> Latest Articles> Difference between PHP global and $GLOBALS keywords and Recommended Usage

Difference between PHP global and $GLOBALS keywords and Recommended Usage

gitbox 2025-06-28

Basic Concepts of global and $GLOBALS in PHP

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.

Differences between global and $GLOBALS

Different Operation Methods

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.

Different Variable Scope

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.

Why You Should Prefer Using the Superglobal Variable

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:

Simplicity and Clarity

Using $GLOBALS allows you to avoid repeatedly declaring the global keyword inside functions, making the code cleaner and simpler.

Better Compatibility

In some highly secured environments, the global keyword may be disabled, but $GLOBALS is not subject to this restriction.

Ease of Access

By using $GLOBALS, global variables can be accessed throughout the entire script, making it easier for other parts of the code to reference them.

Conclusion

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.