Unexpected behavior with variable variables

I was trying to pass a variable containing the name of the superglobal array, I wanted the function to be processed, but I could not get it to work, it just required the variable in question not to exist and return null.

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

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

$sessName   = '_SERVER';

var_dump ($$sessName);

accessSession ($sessName);

      

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

Adding global $_SERVER

to the function did not result in an error, but assigning the $ _SERVER variable to another variable and executing it (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?

+3


source to share


4 answers


PHP: variable variables - manual

Attention

Note that variable variables cannot be used with PHP supergroup arrays inside functions or class methods . The $ this variable is also a special variable that cannot be dynamically referenced.


Decision

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');

      

+3


source


From php.net :



Attention

Note that variable variables cannot be used with PHP Superglobals within functions or class methods. The $ variable is also a special variable that cannot be dynamically referenced.

+2


source


The answer is pretty simple: never use variable variables .
Use arrays instead .

(and yes - you are doing something wrong. No, this is not a bug in PHP.)

-2


source


Use $ GLOBALS. There you go :)

<?php

function accessSession ($sessName)
{
    var_dump ($GLOBALS[$sessName]);
}

$sessName   = '_SERVER';

accessSession ($sessName);

      

-2


source







All Articles