Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Object Cloning and Passing by Reference in PHP

DZone's Guide to

Object Cloning and Passing by Reference in PHP

· Web Dev Zone
Free Resource

Learn how to build modern digital experience apps with Crafter CMS. Download this eBook now. Brought to you in partnership with Crafter Software

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

 

Crafter is a modern CMS platform for building modern websites and content-rich digital experiences. Download this eBook now. Brought to you in partnership with Crafter Software.

Topics:

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}