Why does foreach increase refcount by 2 instead of 1?

不羁岁月 提交于 2019-12-04 12:23:50

问题


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.



来源:https://stackoverflow.com/questions/18158487/why-does-foreach-increase-refcount-by-2-instead-of-1

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