Summary: in this tutorial, you will learn how to copy objects using shallow copying, as well as using deep copying via PHP clone object.
Now, we can create some Person objects:
We’ve created two objects:
$p1 and $p2. Both $p1 and $p2 are references pointing to the different person objects.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:
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:
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.
No comments:
Post a Comment