Tag Archives: Cloning

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?
Continue reading Object Cloning and Passing by Reference in PHP