Search code examples
phpscopevariable-variables

Unexpected behaviour with variable variables


I was trying to pass a variable that contained the name of the superglobal array I wanted a function to process, but I couldn't get it to work, it would just claim the variable in question didn't exist and return null.

I've simplified my test case down to the following code:

function accessSession ($sessName)
{
    var_dump ($$sessName);
}

$sessName   = '_SERVER';

var_dump ($$sessName);

accessSession ($sessName);

The var_dump outside of the function returns the contents of $_SERVER, as expected. However, the var_dump in the function triggers the error mentioned above.

Adding global $_SERVER to the function didn't make the error go away, but assigning $_SERVER to another variable and making that variable global did work (see below)

function accessSession ($sessName)
{
    global $test;
    var_dump ($$sessName);
}

$test       = $_SERVER;
$sessName   = 'test';

var_dump ($$sessName);

accessSession ($sessName);

Is this a PHP bug, or am I just doing something wrong?


Solution

  • PHP: Variable variables - Manual

    Warning

    Please note that variable variables cannot be used with PHP's Superglobal arrays within functions or class methods. The variable $this is also a special variable that cannot be referenced dynamically.


    Solutions

    function access_global_v1 ($var) {
      global    $$var;
      var_dump ($$var);
    }
    

    function access_global_v2 ($var) {
      var_dump ($GLOBALS[$var]);
    }
    

    $test = 123;
    
    access_global_v1 ('_SERVER');
    access_global_v2 ('test');