加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

php – 对象分配与引用

发布时间:2020-12-13 22:47:16 所属栏目:PHP教程 来源:网络整理
导读:我在 PHP Classes and Objects: The Basics上找到了以下示例,但我无法理解后台发生了什么. 有一个声明: When assigning an already created instance of a class to a new variable,the new variable will access the same instance as the object that was
我在 PHP Classes and Objects: The Basics上找到了以下示例,但我无法理解后台发生了什么.

有一个声明:

When assigning an already created instance of a class to a new variable,the new variable will access the same instance as the object that was assigned. This behavior is the same when passing instances to a function. A copy of an already created object can be made by cloning it.

我假设这是默认情况下对象通过引用传递的状态,因此如果要创建真实副本,则应该是clone. (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);

?>

正如在那里被告知的那样,输出如下:

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

我不明白.

如果$assigned = $instance;默认情况下是对象的引用(别名)赋值,而不是$assigned仍然是SimpleClass的一个对象,它保存带有该字符串的$var属性,而NULL被分配给$instance.

解决方法

说$assigned = $instance是一个引用赋值是误导性的.您可以更好地将其视为$instance是一个指针:它具有值(非引用)语义,尽管它的许多副本可以指向同一个对象.

另一方面,$reference =& $instance确实创建了一个别名:当检查另一个变量时,其中一个变量发生的任何事件也会立即可见.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读