求解 为什么foreach 循环数组只会讲指针移动一次到第二位,
程序员文章站
2022-06-05 18:28:56
...
$countries = [
[
'0' => [
'id' =>0
]
],
[
'1' => [
'id' =>1
]
],
];
foreach ($countries as $key => $value) {
print_r(current($countries));
echo '下一个'; print_r(pos($countries)); next($countries);
echo PHP_EOL;
}
?>
回复内容:
$countries = [
[
'0' => [
'id' =>0
]
],
[
'1' => [
'id' =>1
]
],
];
foreach ($countries as $key => $value) {
print_r(current($countries));
echo '下一个'; print_r(pos($countries)); next($countries);
echo PHP_EOL;
}
?>
已经定义的$countries
和foreach循环中的$countries
指向的是同一个zval变量, 因为PHP要节省内存,不需要同样的数据存两份。这时候zval中的refcount
为2. 但是如果在循环中改变$countries
, 比如说
foreach ($countries as &$country) {
$country = 'china'; //因为这里进行了赋值操作, 这里发生了copy-on-write
}
或者
foreach ($countries as $country) {
echo current($countries); //因为current是要传引用的, 这里发生了copy-on-write
}
传了引用, 并且赋值,为触发 copy-on-write
操作, 就是写时复制. 会将zval复制一份, 并把原来的zval的refcount
减1.
每次循环时, 都会执行current,所以每次循环都发生copy-on-write
, 所以每次current 操作的是一份新的zval.
同求这个答案