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

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

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

// Output 2,2

你能帮我看看怎么可能吗?

4

3 回答 3

7

但是请注意,数组内部的引用具有潜在危险。使用右侧的引用进行普通(非引用)赋值不会将左侧变为引用,但数组内的引用会保留在这些普通赋值中。这也适用于数组按值传递的函数调用。

/* 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! */
于 2012-09-06T09:48:32.213 回答
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
于 2012-09-06T11:35:36.537 回答
-1

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

链接php中有指针吗?

于 2012-09-06T09:45:45.613 回答