PHP 7 Backward-Incompatible Changes Document说下面关于foreach:
When used in the default by-value mode, foreach will now operate on a copy of the array being iterated rather than the array itself. This means that changes to the array made during iteration will not affect the values that are iterated.
我正在想明白这是什么意思,我的主要问题是这个代码是否与PHP 5.6中的PHP 7相同?
foreach($array as $elementKey => $element) {
if ($element == 'x') {
unset($array[$elementKey]);
}
}
我的两个问题是:
>这段代码是否仍然可以正常工作?
>如果是这样,你能否解释(可能是例子)PHP 7这个新的变化是什么意思?
编辑
我一直在重新阅读doc声明。我在想,这意味着,如果您在数组中更改项目的值,那么在迭代中获得这些项目时,这些更改将不会在那里。例:
$array = ['x', 'y', 'z'];
$new = [];
foreach($array as $element) {
if ($element == 'x') {
$array[2] = 'a';
}
$new[] = $element;
}
print_r($new);
但是,当我run this example它似乎没有显示任何差异的PHP版本(虽然我从来没有使用这个工具,所以我不知道它是如何工作的)。
我意识到,如果我通过参考,我会得到一个新的。否则我不会。但这两个版本似乎都是这样。
我真正需要知道的是不兼容(例如)?
编辑2
由@NikiC提供的answer link suggested提供了我正在寻找的其他故事:
In most cases this change is transparent and has no other effect than better performance. However there is one occasion where it results in different behavior, namely the case where the array was a reference beforehand:
$array = [1, 2, 3, 4, 5];
$ref = &$array;
foreach ($array as $val) {
var_dump($val);
$array[2] = 0;
}
/* Old output: 1, 2, 0, 4, 5 */
/* New output: 1, 2, 3, 4, 5 */
Previously by-value iteration of reference-arrays was special cases. In this case no duplication occurred, so all modifications of the array during iteration would be reflected by the loop. In PHP 7 this special case is gone: A by-value iteration of an array will always keep working on the original elements, disregarding any modifications during the loop.
这个答案解释了罕见的“特殊情况”,它们在版本之间的区别在于在数组的副本上操作。