我知道 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
survived原始对象($instance
) 被分配给null
,所以显然$assigned
不是引用,而是 $instance 的副本。
那么有什么区别
$assigned = $instance
and
$assigned = clone $instance
对象是内存中的抽象数据。一个变量总是保存一个参考到内存中的这个数据。想象一下$foo = new Bar
创建一个对象实例Bar
在内存中的某个地方,为其分配一些 id#42
, and $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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)