Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable variable string constructed for "$GLOBALS" works within global scope, but not function scope

An important note: $GLOBALS are dirty and evil. Don't use them. Ever. Never ever ever.
Please focus on the fact that it doesn't work and not why you would be doing this in the first place, it is purely a theoretical question about a technical exercise.

This is a rather weird one. I'm attempting to construct a variable variable using a string named $GLOBALS.

From the global scope

Let's see what we get when var_dump()ing this in the global scope.

$g = sprintf('%s%s%s%s%s%s%s', chr(71), chr(76), chr(79), chr(66), chr(65), chr(76), chr(83));
var_dump($$g);

The result is an array of global variables, which you can see here. Great! So, let's try this in a function.

From a function scope

First, let's just make sure that we can actually run an $GLOBALS check within a function.

function globalAllTheThings()
{
    var_dump($GLOBALS);
}

globalAllTheThings();

The result is: it works!! You can see this here.

Now, let's try the first test that we used in the global scope, within the function, and see what happens.

function globalAllTheThings()
{
    $g = sprintf('%s%s%s%s%s%s%s', chr(71), chr(76), chr(79), chr(66), chr(65), chr(76), chr(83));
    var_dump($$g);
}

globalAllTheThings();

For simplicity's sake

You can also try this without the weird obfuscation (don't ask).

function globalAllTheThings()
{
    $g = 'GLOBALS';
    var_dump($$g);
}

globalAllTheThings();

It returns NULL. What's that about?? Why does it return NULL, and what can I do to get this working. Why, you ask? For educational purposes of course, and for science!

ALL THE THINGS, SRSLY

like image 830
Jimbo Avatar asked Oct 03 '22 06:10

Jimbo


1 Answers

Because the manual says so:

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.

http://php.net/manual/en/language.variables.variable.php

It's simply "special". PHP is "special". Superglobals don't play by the same rules as regular variables to begin with. Someone forgot to or decided against making them compatible with variable variables in functions. Period.

like image 83
deceze Avatar answered Oct 12 '22 11:10

deceze