Skip to main content
A global variable in PHP is a variable declared in the main script, outside of any function, method, or class context. It resides in the global symbol table and persists throughout the execution lifecycle of the script. Unlike languages such as C or JavaScript, PHP does not automatically resolve global variables inside local scopes. To access a global variable within a function or method, explicit importation or referencing is required. PHP provides two primary mechanisms for accessing global variables from within a local scope: the global keyword and the $GLOBALS superglobal array.

The global Keyword

The global keyword is used inside a local scope to import a variable from the global symbol table into the local symbol table.
Under the hood, using the global keyword creates a reference (alias) to the global variable. The statement global $value; is semantically equivalent to:
Because it creates a local reference, using the unset() function on a variable imported via the global keyword only severs the local reference; it does not destroy the variable in the global symbol table.

The $GLOBALS Superglobal Array

$GLOBALS is a built-in associative array containing references to all variables currently defined in the global scope. The keys of the array are the names of the global variables, and the values are the contents of those variables. Because $GLOBALS is a superglobal, it is automatically available in all scopes without requiring explicit importation.
Unlike the global keyword, $GLOBALS accesses the actual global variable directly rather than creating a local alias. Consequently, using unset() on an element within the $GLOBALS array will completely destroy the variable in the global symbol table.

Variable Variables and Global Scope

When using variable variables (dynamic variable names) with the global keyword, the variable holding the dynamic name is resolved in the local scope to determine which global variable to import.
PHP imposes a strict limitation regarding superglobals and variable variables: superglobals cannot be used as variable variables inside functions or methods. When a variable variable is evaluated dynamically, PHP does not apply the special scope-bypassing rules of superglobals. Instead, it looks for a standard local variable matching that name.
Tired of Poor PHP Skills? Fix That With Deep Grasping!Learn More