Home » Php » php __clone() and the "shallow clone"

php __clone() and the "shallow clone"

Posted by: admin July 12, 2020 Leave a comment

Questions:

What is meant when the results of __clone() is a “Shallow Clone”?

How to&Answers:

In short: A clone will remain the same references as the original object it is cloned from. Primitive types like strings, or integer are never references (in php) and if you change one reference completely (by replacing the object of a property with another one), this will also not affect the original object. Every property will contain the same and not only the identical object, than the same-named property of the other object.

To create non-swallow copies you must implement __clone(). This is called on the cloned object after the cloning.

public function __clone () {
  $this->myObject = clone $this->myObject;
  // and so on
}

Answer:

This means that when the object is cloned, any properties that are reference variables (variables that refer to other objects, rather than a value) will remain references.

A “non-shallow” clone would set the new object’s to the values of those properties, rather than leaving them as references.

Note: This means that any changes you make to those references in the cloned object will also be made to the values they reference in the “parent” object.