2012-09-06 47 views
5
$arr = array(1); 
$a = & $arr[0]; 

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

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

// Output 2,2 

你能幫我一下嗎?怎麼可能?PHP中的數組引用混淆

+1

你要我們解釋一下它是如何工作的? – Wearybands

+1

他只在arr2上遞增,並且想知道爲什麼arr也是遞增的 – Dukeatcoding

+1

他意味着這種行爲是奇特的,因爲他將$ a設置爲$ arr的引用,但從不使用$ a。這確實很奇怪。 – Sherlock

回答

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! */ 
+0

從來不知道這一點。 +1 – Sherlock

+1

RTFM FTW! :-D +1 – DaveRandom

+1

@DaveRandom請縮寫RTFM FTW。恐怕我錯了;) –

-1

它看起來像$改編[0]和$ ARR2 [0]都指向同一個分配的內存,所以如果你增加的指針之一,INT引腳將在存儲

鏈接Are there pointers in php?被遞增

+2

問題是_why_指向相同的分配內存。 – Sherlock

+0

我還沒看過,但是,$ arr2 = $ arr;似乎不復制$ arr,但只創建一個新的指針,如C – Dukeatcoding

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