有人可以在这里解释一下这里的参考吗? 我知道引用会导致它发生但是怎么样? 为什么只是在2的指数?为什么不是其他人?
我知道引用的内容,但在这个特殊的例子中我丢失了:
$a = array ('zero','one','two');
foreach ($a as &$v) {
}
foreach ($a as $v) {
}
print_r ($a);
输出:
Array ( [0] => zero [1] => one [2] => one )
答案 0 :(得分:4)
在第一个foreach
循环后,$v
将引用$a
中的最后一个元素。
在以下循环中,$v
将分配给zero
然后one
,然后分配给自身(它是参考)。由于先前的分配,它的当前值现在为one
。这就是为什么最后有两个one
。
为了更好地理解:您的代码与以下行相同:
// first loop
$v = &$a[0];
$v = &$a[1];
$v = &$a[2]; // now points to the last element in $a
// second loop ($v is a reference. The last element changes on every step of loop!)
$v = $a[0]; // since $v is a reference the last element has now the value of the first -> zero
$v = $a[1]; // since $v is a reference the last element has now the value of the second last -> one
$v = $a[2]; // this just assigns one = one