PHP 中的数组引用混淆


Array reference confusion in PHP

$arr = array(1);
$a = & $arr[0];
$arr2 = $arr;
$arr2[0]++;
echo $arr[0],$arr2[0];
// Output 2,2

你能帮我怎么可能吗?

但请注意,数组中的引用可能是 危险。使用 右侧的引用不会将左侧变成 引用,但数组中的引用保留在这些普通中 作业。这也适用于数组所在的函数调用 按值传递。

/* 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! */
$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

看起来 $arr[0] 和 $arr 2[0] 指向相同的分配内存,因此如果您在其中一个指针上递增,则 int 将在内存中递增

链接 php 中有指针吗?