3

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?

GordonM
  • 31,179
  • 15
  • 87
  • 129

4 Answers4

3

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');
Community
  • 1
  • 1
Filip Roséen - refp
  • 62,493
  • 20
  • 150
  • 196
2

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.

ghbarratt
  • 11,496
  • 4
  • 41
  • 41
-2

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

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

Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
-2

Use $GLOBALS. There you go :)

<?php

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

$sessName   = '_SERVER';

accessSession ($sessName);
jpic
  • 32,891
  • 5
  • 112
  • 113