8

I can't access superglobals via variable variables inside a function. Am I the source of the problem or is it one of PHP's subtleties? And how to bypass it?

print_r(${'_GET'});

works fine

$g_var = '_GET';
print_r(${$g_var});

Gives me a Notice: Undefined variable: _GET

  • (related)[variable variables with PHP's Superglobal arrays](https://stackoverflow.com/a/58832360/6521116) – LF00 Nov 13 '19 at 07:52

4 Answers4

13

PHP isn't able to recognize that this is a global variable access:
It compiles $_GET and ${'_GET'} to the same opcode sequence, namely a global FETCH_R. ${$g_var} on the other hand will result in a local FETCH_R.

This is also mentioned in the docs:

Superglobals cannot be used as variable variables inside functions or class methods.

NikiC
  • 100,734
  • 37
  • 191
  • 225
  • 1
    Although if you include `global ${$g_var}` inside the function (as you would need to do for any _ordinary_ global variable) then appears to work OK? Is this a viable workaround, or are there other caveats? – MrWhite May 31 '14 at 01:03
2

You can possibly bypass it using $GLOBALS superglobal variable. Instead of writing

function & getSuperGlobal($name) {
    return ${"_$name"};
}

you can write

function & getSuperGlobal($name) {
    return $GLOBALS["_$name"];
}

and the results will equal.

Kubo2
  • 331
  • 3
  • 16
0

It seems that the last PHP versions are dealing fine with that problem. Next code works fine with PHP 5.5.9.

<?php

function foo() {
  print_r(${'_SERVER'});
}

foo();
0

Although, according to the docs here on variable variables, they cannot be used on superglobals inside functions or class methods:

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.

You can simply get around that by declaring them as global variables or referencing them through $GLOBALS variable

Example:

<?php
    function myFunc ($varname) {
        global $$varname;
        var_dump($$varname);
    }
    myFunc('_SERVER'); // works
    myFunc('_POST'); // works


    function mySecondFunc ($varname) {
        var_dump($GLOBALS[$varname]);
    }
    mySEcondFunc('_SERVER'); // works
    mySecondFunc('_POST'); // works

Note: these do not work for $_ENV!