在PHP面向对象编程中,$a=&$b、$a=$b以及$a=clone $b有什么区别?

3
在PHP面向对象编程中,$a = &$b$a = $b$b = clone $a有什么区别?其中$a是一个类的实例。
3个回答

9
// $a is a reference of $b, if $a changes, so does $b.    
$a = &$b; 

// assign $b to $a, the most basic assign.
$a = $b; 

// This is for object clone. Assign a copy of object `$b` to `$a`. 
// Without clone, $a and $b has same object id, which means they are pointing to same object.
$a = clone $b; 

您可以通过引用对象克隆查看更多相关信息。


我也写了几乎一样的东西!+1,尽管我希望你能更详细地解释一下PHP引用和克隆。更新:当然,你在我发表评论的同时更新了你的答案:D - Adi
我不太明白 $a = $b; 和 $a = &$b; 之间的主要区别。如果你看一下这里的第一个例子 http://php.net/manual/en/language.oop5.references.php,它给出了相同的结果。 - Anonim Wd
@AnonimWd 是的,对于对象来说是这样,因为使用 $a = $b 会让它们指向同一个对象,但对于其他类型,当你执行 $a = $b 时,改变 $a 的值不会影响 $b - xdazz

0
// $a has same object id as $b. if u set $b = NULL, $a would be still an object
$a = $b;

// $a is a link to $b. if u set $b = NULL, $a would also become NULL
$a = &$b;

// clone $b and store to $a. also __clone method of $b will be executed
$a = clone $b;

-1
如果你不知道什么是ZVAL结构,以及ZVAL结构中的refcount、is_ref是什么意思,那就花些时间来了解一下PHP垃圾回收

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接