将一个类的实例分配给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获取更多信息.

相关文章

统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
前言 之前做了微信登录,所以总结一下微信授权登录并获取用户...
FastAdmin是我第一个接触的后台管理系统框架。FastAdmin是一...
之前公司需要一个内部的通讯软件,就叫我做一个。通讯软件嘛...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...