php类对象问题

时间:2012-01-31 08:48:57

标签: php

<?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行之间有什么区别?

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

,因为在OOP对象中默认按引用分配。所以$ assign也会有 &安培; $实例。

以上代码的输出是

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

2 个答案:

答案 0 :(得分:2)

  

在OOP对象中默认按引用分配

这不完全正确。

$instance保存的是对象id的值,当您将对象分配给另一个变量时,您只传递了对象ID。

因此,当您执行$assigned = $instance;时,您将$instance保留的对象ID传递给变量$assigned,而$instance = null仅设置变量$instance如果为null,则不会影响$assigned

但是当您执行$reference =& $instance时,您正在创建对变量$instance的引用,因此如果将$instance设置为null,则$reference也将为null。< / p>

答案 1 :(得分:1)

“所以$ assigned也会有&amp; $ instance”

关闭。 $ assigned将成为一个引用,它引用了$ instance在赋值时引用的相同内容。

换句话说:

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

$ assigned复制引用,$引用引用引用该对象的变量。