2012-01-31 35 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中一样,对象通过引用传递给方法,但引用是按值传递的(引用被复制)。

$赋值给引用复制,$引用引用引用对象的变量。