PHP对象分配与克隆

前端之家收集整理的这篇文章主要介绍了PHP对象分配与克隆前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我知道这在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"
}

好的,所以我看到$assign’survived’原始对象($instance)分配给NULL,所以显然$assign不是引用,而是$instance的副本.
那么有什么区别呢?

$assigned = $instance

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

克隆显式创建对象本身的副本,而不仅仅是指向对象的引用.

$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
原文链接:https://www.f2er.com/php/133132.html

猜你在找的PHP相关文章