将一个类的实例赋值给php中的新对象


assign an instance of a class to a new object in 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);
 ?>

I cannot understand the result:

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

谁能告诉我答案,我认为这三个变量指向同一个实例

$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)

通过引用赋值和通过标识符赋值是不同的。从手册:

PHP5 OOP经常被提到的一个关键点是默认情况下,对象是通过引用传递的。这并不完全是真实的。本节用一些例子纠正了这种普遍的想法。

一个PHP引用是一个别名,它允许两个不同的变量写入相同的值。从PHP5开始,对象变量不需要不再包含对象本身作为值。它只包含一个对象标识符,它允许对象访问器找到实际对象。当一个对象通过参数发送、返回或赋值给另一个对象时变量,不同的变量不是别名:它们持有的是指向同一对象的标识符。