PHP 8.1 – Secured $GLOBALS array

PHP 8.1 – Secured $GLOBALS array

globes, globals

Not much would care about this one, but it’s worth to mention that previously you could override the whole $GLOBALS variable with your custom data, now you can only modify its keys/aliases.

The core idea of this change is to move $GLOBALS from being a “real” variable with non-standard semantics, towards being a syntactical variable with two semantics:

  • Accesses of the form $GLOBALS[$var] will refer to the global variable $$var, and support all the usual variable operations, including writes. $GLOBALS[$var] = $value remains supported. A good way to think of this is that $GLOBALS[$var] works the same way as a variable-variable $$var, just accessing the global instead of the local scope.
  • Accesses of the form $GLOBALS (without a direct array dereference) will return the a read-only copy of the global symbol table.

This means that all operations in the following code will continue to work as they do now:

// Continues to work:
$GLOBALS['x'] = 1;
$GLOBALS['x']++;
isset($GLOBALS['x']);
unset($GLOBALS['x']);
// ...anything else using $GLOBALS['x'].

Read-only usage of $GLOBALS will also continue to work:

// Continues to work:
foreach ($GLOBALS as $var => $value) {
    echo "$var => $value\n";
}

More about PHP 8.1

Read about all PHP 8.1 features and changes in here.

Leave a Comment