PHP对象分配与克隆 [英] PHP Object Assignment vs Cloning

查看:75
本文介绍了PHP对象分配与克隆的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道php文档中对此进行了介绍,但对此问题感到困惑.

I know this is covered in the php docs but I got confused with this issue .

从php文档:

From the php docs :

$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的副本.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆