Superglobals and $GLOBALS

Superglobals in PHP are special built-in variables that are always available everywhere — inside functions, inside files, inside classes — without you needing to pass them around. PHP added them way back in 4.1, and they include things like $_GET, $_POST, $_SERVER, $_SESSION, and also GLOBALS, which is the one that maps literally every global variable currently defined.

$GLOBALS itself is just an associative array where each key is the name of a global variable and the value is that variable’s value. So if you define $x = 75 in your main script, PHP automatically creates $GLOBALS['x'] = 75. Inside a function, if you want to access $x, you can’t just echo $x directly — PHP functions don’t automatically “see” variables from the outside. You either:

  • explicitly mark them as global using global $x, or
  • use the superglobal version: $GLOBALS['x'].

So PHP makes you be deliberate. Other languages automatically expose outer-scope variables; PHP doesn’t unless you use global or $GLOBALS.

A variable created in the global scope is global whether you access it as $x or $GLOBALS['x']. But the interesting twist: you can create global variables from inside a function if you assign into $GLOBALS. For example, inside a function, you do $GLOBALS['y'] = 123, and suddenly $y exists globally outside the function — because $GLOBALS is literally the global variable table.

This is basically the foundation: superglobals always exist in every scope, $GLOBALS exposes all global variables as an array, and the global keyword is optional if you prefer to use $GLOBALS directly. Functions don’t automatically inherit outside variables unless you explicitly tell PHP to give them access.