Object Cloning and Passing by Reference in PHP
Join the DZone community and get the full member experience.
Join For FreeIn PHP everything’s a reference! I’ve heard it so many times in my practice. No, these words are too strong! Let’s see some examples.
Passing Parameters by Reference
Clearly when we pass parameters to a function it’s not by reference. How to check this? Well, like this.
function f($param) { $param++; } $a = 5; f($a); echo $a;
Now the value of $a equals 5. If it were passed by reference, it would be 6. With a little change of the code we can get it.
function f(&$param) { $param++; } $a = 5; f($a); echo $a;
Now the variable’s value is 6.
So far, so good. Now what about copying objects?
Objects: A Copy or a Cloning?
We can check whether by assigning an object to a variable a reference or a copy of the object is passed.
class C { public $myvar = 10; } $a = new C(); $b = $a; $b->myvar = 20; // 20, not 10 echo $a->myvar;
The last line outputs 20! This makes it clear. By assigning an object to a variable PHP pass its reference. To make a copy there’s another approach. We need to change $b = $a, to $b = clone $a;
class C { public $myvar = 10; } $a = new C(); $b = clone $a; $b->myvar = 20; // 10 echo $a->myvar;
Arrays by Reference
What about arrays? What if I assign an array to a variable?
$a = array(20); $b = $a; $b[0] = 30; var_dump($a);
What do you think is the value of $a[0]? Well, the answer is: 20! So $b is a copy of the array “a”. Instead you should assign explicitly its reference to make “b” point to “a”.
$a = array(20); $b = &$a; $b[0] = 30; var_dump($a);
Now $a[0] equals 30!
I think this could be useful!
Source: http://www.stoimen.com/blog/2011/10/27/object-cloning-and-passing-by-reference-in-php/
Opinions expressed by DZone contributors are their own.
Comments