$countries = [
<code> [ '0' => [ 'id' =>0 ] ], [ '1' => [ 'id' =>1 ] ],</code>
];
foreach ($countries as $key => $value) {
<code>print_r(current($countries)); echo '下一个'; print_r(pos($countries)); next($countries); echo PHP_EOL; </code>
}
?>
$countries = [
<code> [ '0' => [ 'id' =>0 ] ], [ '1' => [ 'id' =>1 ] ],</code>
];
foreach ($countries as $key => $value) {
<code>print_r(current($countries)); echo '下一个'; print_r(pos($countries)); next($countries); echo PHP_EOL; </code>
}
?>
已经定义的$countries
和foreach循环中的$countries
指向的是同一个zval变量, 因为PHP要节省内存,不需要同样的数据存两份。这时候zval中的refcount
为2. 但是如果在循环中改变$countries
, 比如说
<code class="php"> foreach ($countries as &$country) { $country = 'china'; //因为这里进行了赋值操作, 这里发生了copy-on-write }</code>
或者
<code class="php">foreach ($countries as $country) { echo current($countries); //因为current是要传引用的, 这里发生了copy-on-write }</code>
传了引用, 并且赋值,为触发 copy-on-write
操作, 就是写时复制. 会将zval复制一份, 并把原来的zval的refcount
减1.
每次循环时, 都会执行current,所以每次循环都发生copy-on-write
, 所以每次current 操作的是一份新的zval.
同求这个答案