PHP Pass by reference error after using same var

╄→尐↘猪︶ㄣ 提交于 2019-12-19 10:25:54

问题


Take a look to this code, and help me to understand the result

$x = array('hello', 'beautiful', 'world');
$y = array('bye bye','world', 'harsh');

foreach ($x as $n => &$v) { }

$v = "DONT CHANGE!";

foreach ($y as $n => $v){ }

print_r($x);
die;

It prints:

Array
(
    [0] => hello
    [1] => beautiful
    [2] => harsh
)

Why it changes the LAST element of the $x? it just dont follow any logic!


回答1:


After this loop is executed:

foreach ($x as $n => &$v) { }

$v ends up as a reference to $x[2]. Whatever you assign to $v actually gets assigned $x[2]. So at each iteration of the second loop:

foreach ($y as $n => $v) { }

$v (or should I say $x[2]) becomes:

  • 'bye bye'
  • 'world'
  • 'harsh'



回答2:


// ...
$v = "DONT CHANGE!";
unset($v);
// ...

because $v is still a reference, which later takes the last item in the last foreach loop.

EDIT: See the reference where it reads (in a code block)

unset($value); // break the reference with the last element




回答3:


Foreach loops are not functions.An ampersand(&) at foreach does not work to preserve the values like at functions. So even if you have $var in the second foreach () do not expect it to be like a "ghost" out of the loop.



来源:https://stackoverflow.com/questions/13650898/php-pass-by-reference-error-after-using-same-var

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!