微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐