PHP 对象分配与克隆 [英] PHP Object Assignment vs Cloning
问题描述
我知道这在 php 文档中有介绍,但我对这个问题感到困惑.
I know this is covered in the php docs but I got confused with this issue .
来自 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
survived 原始对象 ($instance
) 被分配给 null
,所以很明显 $assigned
不是引用而是 $instance 的副本.
OK so I see that $assigned
survived the original object ($instance
) being assigned to null
, so obviously $assigned
isn't a reference but a copy of $instance.
那么
$assigned = $instance
和
$assigned = clone $instance
推荐答案
对象是内存中的抽象数据.变量总是在内存中保存对这个数据的引用.想象一下,$foo = new Bar
在内存中的某处创建了一个 Bar
的对象实例,为它分配了一些 id #42
和 $foo
现在持有这个 #42
作为对这个对象的引用.将此引用分配给其他变量通过引用或通常与任何其他值相同.许多变量可以保存此引用的副本,但都指向同一个对象.
Objects are abstract data in memory. A variable always holds a reference to this data in memory. Imagine that $foo = new Bar
creates an object instance of Bar
somewhere in memory, assigns it some id #42
, and $foo
now holds this #42
as reference to this object. Assigning this reference to other variables by reference or normally works the same as with any other values. Many variables can hold a copy of this reference, but all point to the same object.
clone
显式地创建对象本身的副本,而不仅仅是指向对象的引用的副本.
clone
explicitly creates a copy of the object itself, not just of the reference that points to the object.
$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
只是不要将 =&
中的引用"与对象标识符中的引用"混淆.
Just don't confuse "reference" as in =&
with "reference" as in object identifier.
$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 对象分配与克隆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!