Why does foreach increase refcount by 2 instead of

2019-03-21 01:27发布

问题:

NikiC stated in another thread:

Right before [a foreach] iteration the $array is "soft copied" for use in foreach. This means that no actual copy is done, but only the refcount of the zval of $array is increased to 2.

However, my test code is showing a different result:

$array = array(0, 1, 2);
xdebug_debug_zval('array'); // refcount=1, is_ref=0
                            // so far so good
foreach ($array as $key => $value) {
    xdebug_debug_zval('array'); // refcount=3, is_ref=0
}                               // why is refcount 3 instead of 2?

Just by looking at the code, we can see at most two array variables.

Why is refcount 3?

Why isn't refcount 2 after foreach is run?

回答1:

The xdebug_debug_zval() is looking at the $array variable and not the $key variable. if you change your code to:

foreach ($array as $key => $value) {
    echo $key . " : " . $values . "<br>";
    //xdebug_debug_zval('array');

}

The correct values of the array will be returned. I don't have the xdebug function so I can't test what value you put in there.