2012-01-22 17 views
8

在下面的示例中,由$ instance2和$ instance3完成的任何操作都會修改原始對象。對象標識符的複製和對象標識符的引用 - 應該在真實應用程序中使用哪一個?

我的問題是:

如果原來的對象標識符和引用的副本原來的對象標識符做同樣的工作。哪一個應該在實際應用中使用?

對象標識符副本和對象標識符引用有什麼優點和缺點?

我讀 php manual,但在使用方面無法區分,因爲兩者都做同樣的工作。

$instance1 = new test(1); 
$instance2 = $instance1; 
$instance3 =& $instance1; 

//$instance1 -> original object identifier of the new object. 
//$instance2 -> copy of object identifier $instance1 
//$instance3 -> reference to the object identifier $instance1 

回答

5

$instance2具有所述標識符的副本對象測試。因此,它包含與$instance1相同的內容。 $instance3包含對$instance1的引用。所不同的是以下幾點:

$instance1 = new Test(); 
$instance2 = $instance1; 
$instance3 = & $instance1; 

var_dump($instance1 instanceof Test); // True 
var_dump($instance2 instanceof Test); // True 
var_dump($instance3 instanceof Test); // True 

$instance3 = new AnotherTest(); 

var_dump($instance1 instanceof AnotherTest); // True 
var_dump($instance2 instanceof AnotherTest); // False 
var_dump($instance3 instanceof AnotherTest); // True 

如果$instance1被改變,而不是$instance3同樣的輸出將被返回。

但是,如果我們做了以下內容:

$instance1 = new Test(); 
$instance2 = $instance1; 
$instance3 = & $instance1; 

$instance2 = new AnotherTest(); 

var_dump($instance1 instanceof AnotherTest); // False 
var_dump($instance2 instanceof AnotherTest); // True 
var_dump($instance3 instanceof AnotherTest); // False 

所以:

可變至極的修改通過引用(使用&操作數)創建已通過或變量至極它引用的,修改兩者,而複製變量的修改只修改給定變量。

不過,你必須記住,$instance1什麼讓是對象的標識,所以:

$instance1 = new StdClass(); 
$instance2 = $instance1; 

$instance1->my_property = 1; 
var_dump($instance2); // Output: 1 

希望它更清晰了。

+0

你的例子很有意義,但你不應該在PHP中使用'指針'這個詞。 –

+0

我使用了「poitner」這個詞,因爲它們之間的主要區別正是引擎如何處理它們......我不知道如何用不同的方式來描述它。 – Lumbendil

+0

正確的術語是對象標識符:http://php.net/manual/en/language.oop5.references.php –

0

使用PHP5中的對象而不是整個對象,只複製對象標識符。這使得你不需要再引用相同的值,而是可以複製標識符來引用同一個對象。把它用於你的優勢;你可以擺脫&符號。

一個重要的區別是賦值給變量引用會影響原始變量,而賦值給複製的對象標識符則不會。只有修改對象纔會。如果你想以直觀的方式使用OO,這將是而不是使用對象引用的原因。例如:

$a = new stdClass(); 
$a->name = "A"; 

$b = new stdClass(); 
$b->name = "B"; 

// $x is a copy of the object identifier in $a 
$x = $a; 
// $y is a reference to $a 
$y = &$a; 

// this will not affect $a 
$x = $b; 
echo $a->name; // 'A' 

// this will affect $a 
$y = $b; 
echo $a->name; // 'B' 

也參見本文關於爲什麼應避免使用(符號)的引用:

http://schlueters.de/blog/archives/125-Do-not-use-PHP-references.html

+0

你能指出它們之間的任何顯着差異嗎?不使用&只是一個語法好處。否則,兩者都有相同的目的。 –

+0

我添加了一個例子,說明爲什麼利用對象標識符來避免使用變量引用i.c.w。對象。 –