Using __clone()
The __clone()
magic method is triggered on newly cloned objects, where cloning is done using the clone
keyword. The method does not accept any parameters nor does it return any values, as per the following synopsis:
void __clone(void)
When it comes to object cloning, we tend to differentiate deep copy and shallow copy. Deep copy copies everything--all of the objects an object might point to. Shallow copy copies as little as possible, leaving the object references as references where possible. While shallow copy might come in handy as a protection against circular references, replicating all properties whether they are references or values is not always the desired behavior.
The following example demonstrates the implementation of the __clone()
method and the use of the clone
keyword:
<?php class User { public $identifier; public function __clone() { $this->identifier = null; } } $user = new User(); $user->identifier = 'john'; $user2 = clone $user; var_dump...