简体   繁体   English

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

[英]assign an instance of a class to a new object in php

Following is an example in 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);
 ?>

I cannot understand the result : 我不明白结果:

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

Anyone can tell me the answer, I think the three var point the same instance. 任何人都可以告诉我答案,我认为三个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)

Assigning via reference and identifier are different. 通过引用和标识符进行分配是不同的。 From the manual: 从手册中:

One of the key-points of PHP5 OOP that is often mentioned is that "objects are passed by references by default". 经常提到的PHP5 OOP的关键点之一是“默认情况下,对象是通过引用传递的”。 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. PHP引用是一个别名,它允许两个不同的变量写入相同的值。 As of PHP5, an object variable doesn't contain the object itself as value anymore. 从PHP5开始,对象变量不再包含对象本身作为值。 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. 当对象通过参数发送,返回或分配给另一个变量时,不同的变量不是别名:它们持有标识符的副本,该副本指向同一对象。

Check out this answer for more info. 查看此答案以获取更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM