Difference between $a=&$b , $a = $b and $a= clone $b in PHP OOP

一曲冷凌霜 提交于 2019-12-23 17:09:26

问题


What is the difference between $a = &$b, $a = $b and $b = clone $a in PHP OOP? $a is an instance of a class.


回答1:


// $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; 

And check more info with References, Object Cloning.




回答2:


// $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;



回答3:


If you didn't know what is ZVAL structure,and what is refcount,is_ref in ZVAL structure about,just take some time for PHP's garbage collection.



来源:https://stackoverflow.com/questions/11184743/difference-between-a-b-a-b-and-a-clone-b-in-php-oop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!