加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

PHP对象分配与克隆

发布时间:2020-12-13 16:03:18 所属栏目:PHP教程 来源:网络整理
导读:我知道这在php文档中被覆盖,但是我对这个问题感到困惑. 从php文档: $instance = new SimpleClass();$assigned = $instance;$reference = $instance;$instance-var = '$assigned will have this value';$instance = null; // $instance and $reference becom
我知道这在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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读