2012-06-26 89 views

回答

4

那麼另一個使用變量,另一個不是。這在這種情況下導致致命錯誤:

class test { 

    public function __construct(&$a) 
    { 

    } 
} 

$a = true; 

new test($a); 

new test(true); //Fatal error because this cannot be passed by reference 
1

嚴格地說,這取決於如何定義測試。

如果test被限定爲使得輸入參數是passed by reference,然後2將提高一個致命的錯誤,因爲true是一個文字值。

此外,test可能有副作用,這意味着您執行行12重要的順序。

1

它取決於test類的構造函數。在常規通按值構造它們是完全一樣的:

class test { 
    public $b; 
    function __construct($a) { $this->b = $a; } 
} 

這裏,$obj->btrue爲您的聲明,如預期。

如果,另一方面,你是passing by reference如果你改變了全球$a以後你可能會得到不同的結果。例如:

class test { 
    public $b; 
    function __construct(&$a) { $this->b = &$a; } 
} 

$a = true; 
$obj = new test($a); 
$a = false; 

$obj->b會在這種情況下false,因爲它是$a參考!隨着引用,你也可以做它周圍的其他方法,從構造方法中改變$a

class test { 
    function __construct(&$a) { $a = false; } 
} 

$a = true; 
$obj = new test($a); 

$a現在是假的,甚至在全球範圍內!

此外,new test(true)不可能通過引用傳遞,因爲您不能引用文字值,只能引用其他變量。

+0

哇,爲什麼這個低估是超越了我...... :( –

+0

SiGanteng,我同意。會很好的解釋。 –

相關問題