为什么复制的foreach数组的时候,我们并没有在循环修改呢? [英] Why does foreach copy the array when we did not modify it in the loop?

查看:192
本文介绍了为什么复制的foreach数组的时候,我们并没有在循环修改呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在博客中PHP内幕:什么时候的foreach复制,NikiC指出,在code是这样的:

In a blog post "PHP Internals: When does foreach copy", NikiC stated that in a code like this:

片段1

$array = range(0, 100000);
foreach ($array as $key => $value) {
    xdebug_debug_zval('array'); // array is not copied, only refcount is increased
}

的foreach 不会阵列复制,因为的foreach 修改有关 $的唯一的事情阵列是它的内部数组指针。

foreach will not copy the array because the only thing that foreach modifies about $array is it's internal array pointer.

他还指出,在code是这样的:

He also stated that in a code like this:

2片段

$array = range(0, 100000); // line 1
test($array);
function test($array) { 
    foreach ($array as $key => $value) { // line 4
        xdebug_debug_zval('array'); // array is copied, refcount not increased
        // ...
    }
}

的foreach 将数组复制,因为如果没有,在第1行的 $阵列变量会改变了。

foreach will copy the array because if it didn't, the $array variable in line 1 would be changed.

然而,的foreach 修改有关 $阵列的唯一的事情是它的内部数组指针。那么,为什么这很重要,如果 $阵列的内部数组指针在第1行变量发生变化?它没有在片段1无所谓,为什么它的问题在片段2?

However, the only thing that foreach modifies about $array is it's internal array pointer. So why does it matter if the internal array pointer of the $array variable in line 1 is changed? It didn't matter in snippet 1, why did it matter in snippet 2?

为什么的foreach 需要阵列复制片段2,尽管我们并没有改变它的循环?

Why does foreach need to copy the array in snippet 2, even though we did not modify it in the loop?

推荐答案

这是因为在第二种情况下,的 $阵列的是按值传递给函数测试() 。因此, $数组的副本的是在函数内部造的,的foreach()适用于副本。事情会有所不同,如果在的 $阵列的通过引用传递给函数测试()

That is because in the second case, $array is passed by value to the function test(). Hence, a copy of the $array was made inside the function, and the foreach() works on the copy. Things will be different if the $array is passed by reference to the function test().

有关通过值VS引用,<一传上的信息传递href=\"http://stackoverflow.com/questions/373419/whats-the-difference-between-passing-by-reference-vs-passing-by-value\">see这个问题

For information on pass by value vs pass by reference, see this question

这篇关于为什么复制的foreach数组的时候,我们并没有在循环修改呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆