Clone keyword in PHP

Posted on July 30th, 2008 at 5:26 pm

A lot of people do not read PHP manual. That is a fact, they will look for answers to their questions on forums, books, blogs (like this one for example) and so on, while most of the answers they are looking for, are already there … in PHP manual. Or maybe it is me who is weired, because i like to browse PHP.net to see “what’s new”, well can’t really tell.

Well anyway this is what i found interesting: object cloning. It is not a new concept, it was already available in PHP 5.0, so this post may look a bit outdated, but i think it is not, because in my opinion in case of object cloning, PHP manual does a very poor job in explaining what it is and why it is helpful … and this is where i come in ;>.

What is object cloning?

In PHP4, every time we assigned one variable to another (e.g. $var1 = $var2), the first one was the copy of the second one, unless we would use reference (e.g. $var1 =& $var2). Than $var1 would be a link to $var2. What this basically means that whenever we would change value of $var2, value of $var1 would change as well and vice versa, changing $var1 value would affect $var2 value.

In PHP5, scalar variables (integers, strings, real, etc) still are copied, however objects are always referenced, this is a nice way to save memory and in fact most of the time, it is very useful, but sometimes for whatever reason we may need a copy of object, not reference. This is where clone keyword comes handy, it simply creates a copy of an object.

PHP Cloning example

I do not know if i explained everything clearly enough, if not than i think that source code below will do the job for me:

$x = 1;
$y =& $x;
$x++;
echo"$y $x<br>";
class SmallObject
{
    public $field = 0;
}
 
$so = new SmallObject;
 
$so->field++;
 
$soRef = $so;
$soClone = clone $so;
 
$so->field++;
 
echo $so->field;        // outputs: 2
echo $soRef->field;     // outputs: 2
echo $soClone->field;   // outputs: 1

It is very simple code and easy to understand as well. $soRef is a reference or link to $so, so when we changed value of $so->field then value of $soRef also changes. On the other hand $soClone is a copy of $so and have no “relationship” with $so, therfore changing $so->field has no effect on $soClone->field value.

About this author

Greg Winiarski

Greg Winiarski is a freelance PHP and JavaScript programmer. He specializes in web applications and WordPress development.

3 Responses to “Clone keyword in PHP”

  1. Hi! I’m a novice about the PHP, I’m in the process of learning, but anyways i admire your style about cloning the keywords in the php, well i guess i, about to apply that process, thanks once again. God bless

  2. sagar says:

    excellent stuff dude !!…small but a quite comprehensive example …sagar

  3. mike says:

    Great stuff…. will try it on my next website

Leave a Reply