gpt4 book ai didi

PHP 对象分配与克隆

转载 作者:IT王子 更新时间:2023-10-29 00:07:06 25 4
gpt4 key购买 nike

我知道这在 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) 被分配给 null ,所以显然 $assigned 不是引用而是 $instance 的副本。

那有什么区别

 $assigned = $instance 

 $assigned = clone $instance

最佳答案

对象是内存中的抽象数据。变量总是在内存中保存对这些数据的引用。想象一下 $foo = new Bar 在内存某处创建了一个 Bar 的对象实例,并为其分配了一些 id #42$ foo 现在持有这个 #42 作为对这个对象的引用。 通过引用将此引用分配给其他变量,或者通常与任何其他值相同。许多变量可以保存此引用的副本,但都指向同一个对象。

clone 显式创建对象本身的副本,而不仅仅是指向对象的引用。

$foo = new Bar;   // $foo holds a reference to an instance of Bar
$bar = $foo; // $bar holds a copy of the reference to the instance of Bar
$baz =& $foo; // $baz references the same reference to the instance of Bar as $foo

只是不要将 =& 中的“引用”与 对象标识符 中的“引用”混淆。

$blarg = clone $foo;  // the instance of Bar that $foo referenced was copied
// into a new instance of Bar and $blarg now holds a reference
// to that new instance

关于PHP 对象分配与克隆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16893949/

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