3

Here is a result of a random var_dump($GLOBALS):

array(6) {
    ["_GET"] => array(0) {}
    ["_POST"] => array(0) {}
    ["_COOKIE"]=> array(1) {
        ["PHPSESSID"]=> string(26) "o8f2mggog45mq9p5ueafgu5hv6"
    }
    ["_FILES"] => array(0) {}
    ["GLOBALS"] => array(6) {
        ["_GET"] => array(0) {}
        ["_POST"] => array(0) {}
        ["_COOKIE"] => array(1) {
            ["PHPSESSID"] => string(26) "o8f2mggog45mq9p5ueafgu5hv6"
        }
        ["_FILES"] => array(0) {}
        ["GLOBALS"]=>
        *RECURSION*
        ["_SESSION"]=> &array(1) {
            ["somestrings"]=> string(16) "someotherstrings"
        }
    }
    ["_SESSION"] => &array(1) {
        ["somestrings"] => string(16) "someotherstrings"
    }
}

I'm new to PHP and don't understand why PHP need to do that? Won't it use more storage?

wpclevel
  • 2,451
  • 3
  • 14
  • 33

2 Answers2

3

Because by definition, $GLOBALS is a global variable; and since it contains all the globals, it makes sense to have itself contained in it. The recursion is in the definition of these concepts.

And no, it does not uses more storage, because it is a pointer to itself. If it were to use a copy of itself recursively, you would run out of memory.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
sidyll
  • 57,726
  • 14
  • 108
  • 151
  • 2
    _"it makes sense to have itself contained in it"_ On the other hand, I can't think of any situation in which you'd actually need access to it through itself. By definition that would be silly. – Lightness Races in Orbit May 07 '16 at 17:32
  • @LightnessRacesinOrbit I agree, for the end user it is not very useful unless you want just the name of every global (say by listing `$GLOBALS`). Then maybe the access to it was added for completeness, or some other internal reason which I'm not aware of. And thanks for the correction on the name! – sidyll May 07 '16 at 17:35
  • 1
    I think if I were in charge of PHP, after hanging myself I'd conclude that this is a 50/50 toss-up and probably end up with the current solution purely for consistency. – Lightness Races in Orbit May 07 '16 at 17:38
  • @sidyll Then, It's problem of PHP itself? And there are no real reasons to do that? – wpclevel May 07 '16 at 17:44
  • @Dan It is not a problem, and as discussed above, might be just for the completeness – sidyll May 07 '16 at 19:13
2

The $GLOBALS array in php describes the scope containing all of the variables. The funny thing is that $GLOBALS is a pointer to the keyed array of variables... contained in the scope! So, php doesn't store a copy of that array (that would actually require infinite memory), but it just saves a pointer to that array in the array itself so programmers can iterate an array containing all the existing variables.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
NoImaginationGuy
  • 1,795
  • 14
  • 24