Superglobals cannot be accessed through variable variables in a function?

I cannot access superglobals through variable variables inside a function. Am I the source of the problem or is this one of the subtleties of PHP? And how to get around it?

print_r(${'_GET'}); 

works great

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

Gives me a notification: Undefined variable: _GET

+7
source share
3 answers

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

This is also mentioned in docs :

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

+11
source

You can get around it with the $GLOBALS variable of a superglobal variable. Instead of writing

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

You can write

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

and the results will be equal.

+1
source

Recent PHP versions seem to be coping with this problem. The following code works fine with PHP 5.5.9.

 <?php function foo() { print_r(${'_SERVER'}); } foo(); 
0
source

All Articles