When working with PHP object-oriented programming, the concept of creating copies of objects you’ve created can be a little confusing. The main thing you need to understand is that PHP objects are passed byref rather than the standard variable behavior of passing elements byval.
In case you have never heard those terms before, byref means “by reference,” which means that you are essentially assigning an additional name to your original variable. ByVal means “by value,” which means that you are actually copying the variable, creating an entirely new instance of it.
Therefore, when you assign a new variable name to an existing object, as in the following code, you are not actually creating a copy of the object, you are just assigning it an additional name. Any changes made to one will also be made to the other.
$obj = new myClass; $obj2 = $obj;
Therefore, when you do something like the following:
$obj = new myClass; $obj->foo = 'test string'; $obj2 = $obj; $obj2->foo = 'bar'; echo $obj->foo;
"bar" rather than echoing
If you want to create an entirely new copy of the original object, you need to use the “clone” function. By default, the “clone” function simply copies all of the properties already associated with the first object over to a completely new instance.
Using the default “clone” function, the following code:
$obj = new myClass; $obj->foo = 'test string'; $obj->param2 = 'second parameter'; $obj2 = clone $obj; $obj2->foo = 'bar'; echo $obj->foo; echo '<br />'; echo $obj->param2; echo '<br />'; echo $obj2->foo; echo '<br />'; echo $obj2->param2
will produce the following:
test string second parameter bar second parameter
You can also create your own custom clone function within the class definition. If you want to perform special actions when an object is cloned, you will need to set up the clone function within your class definition.
You can find some good information on cloning objects and creating custom clone functions within the PHP manual.