skip to Main Content

I’m reading the PHP documentation for the $GLOBALS array, which says:

As of PHP 8.1.0, write access to the entire $GLOBALS array is no
longer supported

It also says:

As of PHP 8.1.0, $GLOBALS is now a read-only copy of the global symbol
table. That is, global variables cannot be modified via its copy.
Previously, $GLOBALS array is excluded from the usual by-value
behavior of PHP arrays and global variables can be modified via its
copy.

I’m not sure what the above quotes mean, do they mean that I can’t do the following?:

<?php
    $x = "hello";
    
    $GLOBALS["x"] = "bye";
    
    echo $x;
?>

2

Answers


  1. Prior to PHP version 8.1.0 you could assign a value to the entire $GLOBALS array (3v4l):

    $GLOBALS = "Test";
    
    echo $GLOBALS; // Would echo 'Test' prior to PHP 8.1.0
    

    In every more recent PHP version, you will get a fatal error (3v4l):

    Fatal error: $GLOBALS can only be modified using the $GLOBALS[$name] = $value syntax.

    As the error message suggests, you may still assign a value using the array syntax.

    $GLOBALS["myVar"] = "Test";
    
    echo $GLOBALS["myVar"]; // Will echo 'Test'
    
    Login or Signup to reply.
  2. This is a consequence of the Restrict $GLOBALS usage RFC.

    The proposal states:

    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.

    and later explicitly confirms that $GLOBALS['x'] = 1; should continue to work. However, it is now a special case, and $GLOBALS can no longer, in general, be used with operations that would modify it in place:

    function set(&$array, $key, $val) {
        $array[$key] = $val;
    }
    
    $arr = ['x' => 0];
    
    set($arr, 'x', 1);        // works
    set($GLOBALS, 'x', 1);    // no longer works as of PHP 8.1
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search