到目前为止,我们一直在使用 PHP 5.5,代码似乎一切都顺畅。由于将其升级到 7,大多数 foreach() 似乎都存在不一致的行为。
例如:考虑下面的片段:
$array = array('a', 'b', 'c');
self::testForeach($array);
.
.
.
// $array is passed by reference
public static function testForeach(&$array) {
foreach ($array as $key => $val) {
//produces a, b as an output in PHP 5
//produces a, b, c as an output in PHP 7
var_dump($val);
if ($val == 'b') {
//remove 'c' from the array
unset($array[2]);
}
}
}
PHP 5.5 中的行为:
$array is passed by reference to testForeach() function. So removing "c" from $array inside the loop would directly modify the original array. Hence, the iterated values would be a, b and not c as it gets removed from the array in between.
PHP 7 中的行为:
$array is passed by reference to testForeach() function. When $array is looped over foreach(), a copy is made say $arrayCopy (according to the doc) which is being iterated over the loop. So removing "c" value from $array would have no effect and will loop all the values contained in the $arrayCopy. Hence the output - a, b, c.
将 foreach 更改为 pass-by-ref 对我来说不是一个解决方案,因为我的项目中有太多的 foreach,我无法 grep 和修改它们中的每一个。
在最新版本中是否对此类行为进行了任何其他处理。任何可以突出显示它们的工具/解析器?
有什么提示/想法吗?
谢谢!
最佳答案
仅当您通过引用循环数组时:foreach ( $array as $key => &$val ) {
Afaik 然后没有制作副本。 http://php.net/manual/en/control-structures.foreach.php
警告:在这种情况下,$val 仍然是指向数组最后一个元素的指针,最佳做法是取消设置它。
foreach ( $array as $key => &$val ) {
<?php
$array = array();
testForeach( $array );
// $array is passed by reference
function testForeach( &$array )
{
$array = array( 'a', 'b', 'c' );
foreach ( $array as $key => &$val ) {
//produces a, b as an output in PHP 5
//produces a, b, c as an output in PHP 7
var_dump( $val );
if ( $val == 'b' ) {
//remove 'c' from the array
unset( $array[ 2 ] );
}
}
unset($val);
}
关于php - 在 PHP 7 中处理 foreach by-ref,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39530753/