This base class automatically clones attributes of type object or array values of type object recursively. Just inherit your own classes from this base class.
<?php
class clone_base
{
public function __clone()
{
$object_vars = get_object_vars($this);
foreach ($object_vars as $attr_name => $attr_value)
{
if (is_object($this->$attr_name))
{
$this->$attr_name = clone $this->$attr_name;
}
else if (is_array($this->$attr_name))
{
// Note: This copies only one dimension arrays
foreach ($this->$attr_name as &$attr_array_value)
{
if (is_object($attr_array_value))
{
$attr_array_value = clone $attr_array_value;
}
unset($attr_array_value);
}
}
}
}
}
?>
Example:
<?php
class foo extends clone_base
{
public $attr = "Hello";
public $b = null;
public $attr2 = array();
public function __construct()
{
$this->b = new bar("World");
$this->attr2[] = new bar("What's");
$this->attr2[] = new bar("up?");
}
}
class bar extends clone_base
{
public $attr;
public function __construct($attr_value)
{
$this->attr = $attr_value;
}
}
echo "<pre>";
$f1 = new foo();
$f2 = clone $f1;
$f2->attr = "James";
$f2->b->attr = "Bond";
$f2->attr2[0]->attr = "Agent";
$f2->attr2[1]->attr = "007";
echo "f1.attr = " . $f1->attr . "\n";
echo "f1.b.attr = " . $f1->b->attr . "\n";
echo "f1.attr2[0] = " . $f1->attr2[0]->attr . "\n";
echo "f1.attr2[1] = " . $f1->attr2[1]->attr . "\n";
echo "\n";
echo "f2.attr = " . $f2->attr . "\n";
echo "f2.b.attr = " . $f2->b->attr . "\n";
echo "f2.attr2[0] = " . $f2->attr2[0]->attr . "\n";
echo "f2.attr2[1] = " . $f2->attr2[1]->attr . "\n";
?>