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

Add user login and MFA to your next project in minutes. Create a free Okta developer account, drop in one of our SDKs to your application and get back to building.

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/

 

Launch your application faster with Okta’s user management API. Register today for the free forever developer edition!

Topics:

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}