What does “*RECURSION*” mean when printing $GLOBAL

2020-03-17 07:16发布

问题:

When I print $GLOBALS using this code:

<?php print_r($GLOBALS); ?>

I get this output:

Array ( [_GET] => Array ( ) [_POST] => Array ( ) [_COOKIE] => Array ( ) [_FILES] => Array ( ) [GLOBALS] => Array *RECURSION* )

What does "*RECURSION*" mean in this case, and why are $_SERVER, $_REQUEST, etc. not printed as well?

回答1:

See this part of PHP Manual:

Keep in mind that $GLOBALS is, itself, a global variable. So code like this won't work:

<?php
    print '$GLOBALS = ' . var_export($GLOBALS, true) . "\n";
?>

This results in the error message: "Nesting level too deep - recursive dependency?"

You already have retrieved the whole list - you just cannot display part of it (the one containing a recursion, because you would have timeout rather than anything meaningful).

When it comes to $_REQUEST, it is a derivative from $_GET, $_POST and $_COOKIE, so its content is redundant.

EDIT: There is an old bug / feature, that seems to be populating $GLOBALS with $_SERVER and $_REQUEST when they are accessed. So try to access $_REQUEST and hope it helps. Anyway, it can be found in $GLOBALS after that: ideone.com/CGetH



回答2:

$GLOBALS contains itself as an array. In the PHP reference you can find the definition of $GLOBALS:

An associative array containing references to all variables which are currently defined in the global scope of the script. The variable names are the keys of the array.

Therefore, it has to contain also itself, which leads to a recursion.

The other arrays are probably just empty, since nothing else has happened in your script.

There is an old joke about recursion: "To understand recursion, you must understand recursion".

BTW: It outputs _SERVER on my computer.



回答3:

When you have an object pointing to itself... i.e., it'll just go in circles.