为什么foreach增加了2,而不是1? [英] Why does foreach increase refcount by 2 instead of 1?
问题描述
在[foreach]迭代之前,对于
在foreach中使用$ array
是软拷贝。这意味着没有实际的拷贝完成,但是只有$ array
的zval的
refcount增加到2。
然而,我的测试代码显示了不同的结果:
$ array = array(0,1,2);
xdebug_debug_zval('array'); // $ refcount = 1,is_ref = 0
//到目前为止好
foreach($ array为$ key => $ value){
xdebug_debug_zval('array'); // refcount = 3,is_ref = 0
} //为什么是refcount 3而不是2?
只要查看代码,我们最多可以看到两个数组变量。 b
$ b为什么是refcount 3
?
为什么不是refcount <$ code> foreach 是否运行?
xdebug_debug_zval()正在查看$ array变量而不是$ key变量。
如果您将您的代码更改为:
$ $ $ $ $ $ foreach $ $ $ $ $ $ $ $ $ $ $
echo $ key。 :。 $值。 <峰; br> 中;
// xdebug_debug_zval('array');
$正确的数组值将被返回。我没有xdebug函数,所以我不能测试你在那里放什么值。
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?
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.
这篇关于为什么foreach增加了2,而不是1?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!