我试图了解引用如何工作的来龙去脉,但我在试图遵循编程逻辑时遇到了困难,即当代码在数组中循环时,它到底在做什么。我正试图一步一步地了解正在发生的事情。
我已经通读了PHP.net的文章,并理解当在数组的foreach中使用引用时,必须取消设置变量。我也知道下面的代码不是最好的代码。我使用它只是为了学习php解释器如何运行不同代码的编程流逻辑。
我的问题是,如果我不取消设置($v),这段代码每次循环通过这个数组时都要做什么,以使它输出以下内容?换言之,它是如何一步一步地让数组将"two"作为第一个元素,将"three"作为第二个元素,并将"three3"作为第三个元素的?
$arr = array(1=>'one',2=>'two',3=>'three');
foreach($arr as $k=>$v){
$v = &$arr[$k];
$v .= $k;
echo $v . "'n";
//unset($v) .... if I use unset($v) here, then the resulting $arr is correct.
}
输出是…
one1
two2
three3
Array
(
[1] => two
[2] => three
[3] => three3
)
非常感谢你的帮助!!
第一次通过循环
foreach($arr as $k=>$v){ // Sets $v to a value of "one"
$v =& $arr[$k]; // Sets $v as a reference to $arr[1] ("one")
$v .= $k; // Sets $v (and hence also $arr[1]) to "one1"
第二次通过环路
foreach($arr as $k=>$v){ // Sets $v to a value of "two"...
// because $v is already set as a reference to $arr[1] from the previous loop,
// this changes $arr[1] to a value of "two"
$v =& $arr[$k]; // Sets $v as a reference to $arr[2] ("two")
// It no longer references $arr[1] so $arr[1] will not be changed any further
$v .= $k; // Sets $v (and hence also $arr[2]) to "two2"
第三次通过环路
foreach($arr as $k=>$v){ // Sets $v to a value of "three"...
// because $v is already set as a reference to $arr[2] from the previous loop,
// this changes $arr[2] to a value of "three"
$v =& $arr[$k]; // Sets $v as a reference to $arr[3] ("three")
// It no longer references $arr[2] so $arr[2] will not be changed any further
$v .= $k; // Sets $v (and hence also $arr[3]) to "three3"
如果使用unset()
首次通过环路
foreach($arr as $k=>$v){ // Sets $v to a value of "one"
$v =& $arr[$k]; // Sets $v as a reference to $arr[1] ("one")
$v .= $k; // Sets $v (and hence also $arr[1]) to "one1"
unset($v); // Unsets $v as a reference, it no longer points to $arr[1]
第二次通过环路
foreach($arr as $k=>$v){ // Sets $v to a value of "two"...
// As $v is no longer set as a reference to $arr[1],
// this leaves $arr[1] unchanged by this loop
$v =& $arr[$k]; // Sets $v as a reference to $arr[2] ("two")
$v .= $k; // Sets $v (and hence also $arr[2]) to "two2"
unset($v); // Unsets $v as a reference, it no longer points to $arr[2]
第三次通过环路
foreach($arr as $k=>$v){ // Sets $v to a value of "three"...
// As $v is no longer set as a reference to $arr[2],
// this leaves $arr[2] unchanged by this loop
$v =& $arr[$k]; // Sets $v as a reference to $arr[3] ("three")
$v .= $k; // Sets $v (and hence also $arr[3]) to "three3"
unset($v); // Unsets $v as a reference, it no longer points to $arr[3]