Search code examples
phpclone

php __clone() and the "shallow clone"


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


Solution

  • 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
    }