Skip to main content

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:

Prompt
Write a PHP script that creates a global variable $x with value 75, then defines a function that uses $GLOBALS to echo $x. Call the function.
Output: PHP script

Without $GLOBALS

Leave out $GLOBALS and the function can't see the global variable, so PHP gives you nothing, or an error:

Prompt
Write a PHP script that creates a global variable $x with value 75, then defines a function that tries to echo $x without using $GLOBALS or the global keyword. Call the function.
Output: PHP script

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:

Prompt
Write a PHP script that creates a global variable $x with value 75, then defines a function that uses the global keyword to access $x and echo it. Call the function.
Output: PHP script

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:

Prompt
Write a PHP script that creates a variable $x with value 100, then echoes it using both $GLOBALS['x'] and $x directly.
Output: PHP script

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:

Prompt
Write a PHP script that creates two global variables $x and $y, then defines a function that uses $GLOBALS to add them and store the result in a new global variable $z. Call the function and echo $z.
Output: PHP script