Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Superglobals can't be accessed via variable variables in a function?

Tags:

php

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

like image 283
Alexandre Dieulot Avatar asked Nov 09 '11 20:11

Alexandre Dieulot


People also ask

What is PHP Superglobals variable?

Some predefined variables in PHP are "superglobals", which means that they are always accessible, regardless of scope - and you can access them from any function, class or file without having to do anything special.

What is a Superglobal variable?

Superglobals are special types of variables because they can be accessed from any scope. The accessibility can be from any file, class, or even function without the implementation of any special code segments. Superglobal variables are inbuilt and predefined.

Which Superglobal variable holds information about headers paths and script locations?

$_SERVER is a PHP super global variable which holds information about headers, paths, and script locations.


1 Answers

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.

like image 191
NikiC Avatar answered Sep 20 '22 20:09

NikiC