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

匿名 (未验证) 提交于 2019-12-03 08:48:34

问题:

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!

回答1:

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.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!