Page 1 of 1

Deep clone

Posted: Wed Dec 13, 2006 7:03 pm
by Ollie Saunders
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))

Code: Select all

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};
        }
    }
}
Output: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).

I'm trying to avoid endless:

Code: Select all

public function __clone()
{
    parent::__clone();
    $this->_obj = clone $this->_obj;
    $this->_obj1 = clone $this->_obj1;
    $this->_obj2 = clone $this->_obj2;
}
in my classes all over the place.

Posted: Wed Dec 13, 2006 9:11 pm
by feyd
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. ;)

Posted: Thu Dec 14, 2006 5:22 am
by Ollie Saunders
aww :(

well...yeah

Posted: Thu Dec 14, 2006 7:18 am
by Chris Corbyn
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.