簡體   English   中英

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]和$ arr2 [0]指向相同的已分配內存,因此如果你在其中一個指針上遞增,則int將在內存中遞增

鏈接在PHP中有指針嗎?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM