James Vu
James Vu

Reputation: 2471

Why PHP needs to store the same global data recursively?

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?

Upvotes: 3

Views: 101

Answers (2)

NYG
NYG

Reputation: 1817

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.

Upvotes: 2

sidyll
sidyll

Reputation: 59297

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.

Upvotes: 3

Related Questions