Summary: in this tutorial, you will learn how to copy objects using shallow copying, as well as using deep copying via PHP clone object.
Let’s start creating a simple Person
class for the sake of demonstration.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | php class Person{ private $ssn; private $firstName; private $lastName; public function __construct($ssn,$firstName,$lastName){ $this->ssn = $ssn; $this->firstName = $firstName; $this->lastName = $lastName; } public function __destruct(){ echo sprintf("Person with SSN# %s is terminated. ", $this->ssn); } public function __toString(){ return sprintf("SSN: %s, Name: %s, %s ", $this->ssn, $this->lastName, $this->firstName); } } |
Now, we can create some Person objects:
1 2 3 4 5 | $p1 = new Person('1234567888', 'Doe', 'John'); echo $p1; $p2 = new Person('1234567889','Grace','Dell'); echo $p2; |
We’ve created two objects: $p1
and $p2
. Both $p1
and $p2
are references pointing to the different person objects.
What will happen if we do the following:
1 | $p2 = $p1; |
Both $p1
and $p2
are now pointing to the same object. However the destructor of the $p2
is called because the object that $p2
is pointing is no longer in used or out of scope.
As we have seen, no real object was created when we assigned $p1
to $p2
, only the reference was changed. The way that we’ve copied object is known as shallow copy.
To perform a deep copy that results in creating a new object, we use clone
operator as follows:
1 | $p2 = clone $p1; |
When we execute the statement, the $p2
reference is pointing to the newly created object. In addition, during the execution, the __clone()
magic methods is invoked automatically.
We can add the __clone()
magic methods to the Person
class to see how it works.
1 2 3 | public function __clone(){ echo 'Copying object <br>'; } |
You can download the PHP clone object script files via the following link:
PHP Clone Object (1584 downloads)In this tutorial, we have discussed the differences between shallow copy and deep copy when we copy an object. We also showed you how to use the clone
operator to perform a deep copy of an object.