gpt4 book ai didi

php - 对象分配与引用

转载 作者:可可西里 更新时间:2023-10-31 23:41:53 26 4
gpt4 key购买 nike

我在 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 的对象 包含带有该 string$var 属性,而 NULL 被分配给 $instance .

最佳答案

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

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

关于php - 对象分配与引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14559100/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com