Brook Julias
Brook Julias

Reputation: 2105

php __clone() and the "shallow clone"

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

Upvotes: 7

Views: 2076

Answers (2)

KingCrunch
KingCrunch

Reputation: 132051

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
}

Upvotes: 3

BraedenP
BraedenP

Reputation: 7215

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.

Upvotes: 8

Related Questions