Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 411
GordonM Avatar asked Mar 18 '26 18:03

GordonM


2 Answers

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');
like image 141
Filip Roséen - refp Avatar answered Mar 21 '26 09:03

Filip Roséen - refp


From php.net:

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.

like image 30
ghbarratt Avatar answered Mar 21 '26 08:03

ghbarratt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!