[英]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]和$ arr2 [0]指向相同的已分配内存,因此如果你在其中一个指针上递增,则int将在内存中递增
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.