【问题标题】:I can't understand the output of the given code below [duplicate]我无法理解下面给定代码的输出[重复]
【发布时间】:2023-03-18 17:53:01
【问题描述】:
Input:
<?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);
?>


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

链接:http://php.net/manual/en/language.oop5.basic.php

请给出足够的解释。为什么 $assigned 最后给出了那个输出。

【问题讨论】:

  • 让我们从您认为它不应显示的原因开始,我们可以尝试帮助您理解。
  • 因为$assigned 指向的内存块与$instance,$reference 指向的内存块不同。清洁一个块不会清洁另一个。

标签: php


【解决方案1】:

Instance不是对象,只是一个指向对象的指针,所以赋值是独立的。

$instance = new SimpleClass();  // instance points to instantiated object
$assigned   =  $instance;       // assigned also points to same object
$reference  =& $instance;       // reference points to instance which points to object

$instance->var = '$assigned will have this value'; // all get set with this

$instance = null; // instance and reference no longer point to the object, assigned still does

如果您在$instance-&gt;var = '$assigned will have this value'; 之后直接var_dump() 所有三个,您会看到每个 var 都有值。

引用指向实例,实例指向对象。分配给对象的点与实例没有任何关系。

希望这会有所帮助!

【讨论】:

  • 感谢您的解释
【解决方案2】:

也许documentation 会帮助你理解参考文献。 检查第一个示例,尤其是 cmets。

您很容易理解 $reference$instance 是“绑定”在一起的,而 $assigned 则不是。

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-06-11
    • 2022-11-21
    • 2020-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-17
    相关资源
    最近更新 更多