$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.
同求這個答案