PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!
Does anybody have any techniques for deep clones where the objects inside the object being cloned are also cloned. I tried this but it doesn't work for privates or protected (same with foreach ($this))
private $a, $b, $c;
public function __construct()
{
$this->a = new stdClass();
$this->b = new stdClass();
$this->c = new stdClass();
}
public function __clone()
{
$reflection = new ReflectionClass($this);
foreach ($reflection->getProperties() as $prop) {
$prop = $prop->getName();
if (is_object($this->{$prop})) {
echo $prop;
$this->{$prop} = clone $this->{$prop};
}
}
}
Its important the solution works with inheritance as ideally I'd like to implement this method in an abstract superclass and have it affect all subclasses (privates have been used).
The class must handle the clone itself. Sure, a high level implementation could handle the public object instances, but it's impossible to handle protected and private ones. You would end up needing the magic clone overloaded anyways. You may as well do it right rather than half.
In other languages, for an object to be cloned it must be declared cloneable, which means in implements a clone method. All children then need to implement a clone method. You can't (fully) clone an object which doesn't "want" to cloned.