Deep clone

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!

Moderator: General Moderators

Post Reply
User avatar
Ollie Saunders
DevNet Master
Posts: 3179
Joined: Tue May 24, 2005 6:01 pm
Location: UK

Deep clone

Post 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.
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post 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. ;)
User avatar
Ollie Saunders
DevNet Master
Posts: 3179
Joined: Tue May 24, 2005 6:01 pm
Location: UK

Post by Ollie Saunders »

aww :(

well...yeah
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Post 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.
Post Reply