Object Cloning and Passing by Reference in PHP

In 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 by reference in PHP can be tricky!
Some developers think that everything's passed by reference in PHP.

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!

3 thoughts on “Object Cloning and Passing by Reference in PHP

  1. Your first two chunks of code are exactly the same (if my diff is correct)- I think you probably meant to include an ampersand in your function there…

Leave a Reply

Your email address will not be published. Required fields are marked *