将一个类的实例分配给php中的新对象

以下是
manual中的示例:

<?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);
 ?>

我无法理解结果:

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

任何人都可以告诉我答案,我认为三个var指向同一个实例.

最佳答案

$instance = new SimpleClass(); // create instance
$assigned   =  $instance; // assign *identifier* to $assigned
$reference  =& $instance; // assign *reference* to $reference 

$instance->var = '$assigned will have this value';
$instance = null; // change $instance to null (as well as any variables that reference same)

通过引用和标识符分配是不同的.从手册:

One of the key-points of PHP5 OOP that is often mentioned is that
“objects are passed by references by default”. This is not completely
true. This section rectifies that general thought using some examples.

A PHP reference is an alias, which allows two different variables to
write to the same value. As of PHP5, an object variable doesn’t
contain the object itself as value anymore. It only contains an object
identifier which allows object accessors to find the actual object.
When an object is sent by argument, returned or assigned to another
variable, the different variables are not aliases: they hold a copy of
the identifier, which points to the same object.

查看this answer获取更多信息.

点赞