What is the difference between $a = &$b
, $a = $b
and $b = clone $a
in PHP OOP? $a
is an instance of a class.
Asked
Active
Viewed 2,276 times
3 Answers
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;
And check more info with References, Object Cloning.

xdazz
- 158,678
- 38
- 247
- 274
-
I was also writing almost the same! +1, although I wish you explained PHP referencing and cloning a bit more. Update: and of course you updated your answer same time I posted the comment :D – Adi Jun 25 '12 at 07:10
-
i don't understand exactly what is the main difference between $a = $b; and $a = &$b; If you look at the first example here http://php.net/manual/en/language.oop5.references.php it gives the same result – Anonim Wd Jun 25 '12 at 07:31
-
@AnonimWd Yes, for objects, because use `$a = $b` will let they pointing to same object, but for other type, when you do `$a = $b`, change the value of `$a` will not affect `$b`. – xdazz Jun 25 '12 at 09:25
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
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.

Lake
- 813
- 4
- 6