2012-01-31 65 views
1
<?php 

$instance = new SimpleClass(); 

$assigned = $instance; 
$reference =& $instance; 

$instance->var = '$assigned will have this value'; 

$instance = null; // $instance and $reference become null 

var_dump($instance); 
var_dump($reference); 
var_dump($assigned); 
?> 

下面給出2行有什麼區別?php類對象問題

$assigned = $instance; 
$reference =& $instance; 

在OOP對象中默認情況下是通過引用來分配的。所以$分配的也將有 & $實例。的上面的代碼

輸出是

NULL 
NULL 
object(SimpleClass)#1 (1) { 
    ["var"]=> 
    string(30) "$assigned will have this value" 
} 

回答

2

在OOP對象被默認以引用的分配

這並不是完全真實的。

$instance是什麼$instance是對象ID的值,當您將對象分配給另一個變量時,只傳遞對象ID。

所以當你做$assigned = $instance;,要傳遞哪些$instance持有的變量$assigned對象ID,並$instance = null只設置變量$instance爲空,什麼都不會影響到$assigned

但是當你做$reference =& $instance,要創建的變量$instance一個參考,因此,如果您設置$instance爲null,$reference也將是空的。

1

「所以$分配也將有& $實例」

關閉。 $ assigned將成爲引用與$實例在賦值時引用的相同內容的引用。

換句話說:

<?php 

$instance = new SimpleClass(); 


$assigned = $instance; //$assigned now references SimpleClass instance (NOT $instance) 
//Other than both pointing the same thing, the two variables are not related at all (sort of... :p) 


$reference =& $instance; 

//$reference does not point at the SimpleClass instance like $assigned does, but rather it points at $instance which points at the SimpleClass instance. It is, in a sort of incorrect way, a reference to the reference. 

//$instance still references the SimpleClass instance here, so it does what you'd expect 
$instance->var = '$assigned will have this value'; 

$instance = null; // $instance and $reference become null 

//They both become null because $reference references $instance. In the same way that: 

$a = 5; 
$b =& $a; 

$a = 3; //$b now equals 3. 

//Since the reference held in $instance is wiped, $reference's value is wiped too (since it points to that same reference 

這一點的一個令人費解的解釋,我很害怕,但希望它橫跨得到點。重點是:變量不存儲對象;變量引用對象。對象不會默認複製,而是複製引用。

$ a = new ...; $ b = $ a;

這將複製引用,而不是對象。 $ b =克隆$ a;會複製對象。

如果您對Java很熟悉,就好像在Java中一樣,對象通過引用傳遞給方法,但引用是按值傳遞的(引用被複制)。

$賦值給引用複製,$引用引用引用對象的變量。