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?
source to share
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');
source to share