PHP中的数组引用混淆

时间:2012-09-06 09:41:51

标签: php

$arr = array(1);
$a = & $arr[0];

$arr2 = $arr;
$arr2[0]++;

echo $arr[0],$arr2[0];

// Output 2,2

你能帮我解决一下这个问题吗?

3 个答案:

答案 0 :(得分:7)

  

但请注意,数组内部的引用是可能的   危险的。使用a执行正常(不是通过引用)赋值   右侧的参考不会将左侧变为a   引用,但数组内的引用保留在这些正常情况下   分配。这也适用于数组所在的函数调用   通过价值传递。

/* Assignment of array variables */
$arr = array(1);
$a =& $arr[0]; //$a and $arr[0] are in the same reference set
$arr2 = $arr; //not an assignment-by-reference!
$arr2[0]++;
/* $a == 2, $arr == array(2) */
/* The contents of $arr are changed even though it's not a reference! */

答案 1 :(得分:0)

$arr = array(1);//creates an Array ( [0] => 1 ) and assigns it to $arr
$a = & $arr[0];//assigns by reference $arr[0] to $a and thus $a is a reference of $arr[0]. 
//Here $arr[0] is also replaced with the reference to the actual value i.e. 1

$arr2 = $arr;//assigns $arr to $arr2

$arr2[0]++;//increments the referenced value by one

echo $arr[0],$arr2[0];//As both $aar[0] and $arr2[0] are referencing the same block of memory so both echo 2

// Output 22

答案 2 :(得分:-1)

看起来$ arr [0]和$ arr2 [0]指向相同的已分配内存,所以如果你在其中一个指针上递增,那么int将在内存中递增

链接Are there pointers in php?