PHP Reference ยท Variables and Constants
PHP $GLOBALS superglobal
Reference for PHP $GLOBALS: read and write global variables from any scope, how it changed in PHP 8.1 and why function parameters are usually better.
$GLOBALS is a superglobal array that holds every variable of the global scope, keyed by variable name. $GLOBALS["total"] is the variable $total of the main script, reachable from inside any function without the global keyword.
Since PHP 8.1, $GLOBALS is treated as a read-only copy of the global symbol table as a whole. You may still read it and write single elements with $GLOBALS["name"] = value, but you cannot assign to the array itself ($GLOBALS = []) or pass it by reference to functions that modify it.
<?php $counter = 1; function bump(): void { $GLOBALS["counter"]++; }
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Syntax
$GLOBALS["variable_name"] $GLOBALS["variable_name"] = $value; unset($GLOBALS["variable_name"]);
Type: array<string, mixed>, a read-only copy since PHP 8.1 (individual elements stay writable).
Usage notes
- Alternative to
global.global $x;imports a variable into the function;$GLOBALS["x"]accesses it directly. Both create hidden dependencies. - Reading a missing key warns.
$GLOBALS["nope"]raisesUndefined global variable $nope. Use??orisset(). - Creates globals. Writing a new key inside a function defines a new global variable that code outside can read.
- PHP 8.1 restrictions. Disallowed:
$GLOBALS = [],$GLOBALS += [...],$x = &$GLOBALS,unset($GLOBALS), and passing$GLOBALSto functions that take it by reference.foreach ($GLOBALS as ...)and$copy = $GLOBALSstill work, and$copyis a detached copy. - Includes the superglobals.
$GLOBALSalso lists_GET,_POST,_SERVERand so on. JIT superglobals such as_ENVand_REQUESTappear only if the script mentions them. Alsoargvandargcin the command line. - Avoid in application code. Global state makes functions hard to test and reason about. Pass values as parameters, return results, or use objects and dependency injection.
- Static variables and constants (see
globalandstatic,constanddefine) are cleaner ways to keep shared values. - Superglobals in functions. Dynamic access such as
$GLOBALS[$name]is the supported way to reach a global variable by a name stored in a string. - Scope of
unset.unset($GLOBALS["x"])removes the global;global $x; unset($x);only removes the local link.