note 88313 deleted from language.oop5.cloning by danbrown
| From: | danbrown@php.net | Date: | Tue, 20 Jan 2009 03:19:29 +0000 |
| Subject: | note 88313 deleted from language.oop5.cloning by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-149501@lists.php.net to get a copy of this message | ||
Note Submitter: Anonymous
----
To cheetah:
The result of your way of deep clone is not what we expect sometimes.Just take notice of this code:
<?php
class A
{
public $b;
public function __construct ()
{
$this->b = new B($this);
}
function __clone()
{
foreach($this as $key => $val) {
if(is_object($val)||(is_array($val))){
$this->{$key} = unserialize(serialize($val));
}
}
}
}
class B
{
public $a;
public function __construct ($a = NULL)
{
$this->a = $a;
}
}
$a = new A();
$b = $a->b;
echo $a; //1
echo $b; //2
echo $b->a; //1
$a2 = clone $a;
$b2 = $a2->b;
echo $a2; // 3
echo $b2; //4
echo $b2->a; //5
?>
The output is :
Object id #1
Object id #2
Object id #1
Object id #3
Object id #4
Object id #5
from which , we know, before our clone , $a and $b both have a property referrence to each
other,but after clone,$a2 has $b2,but $b2 doesn't has $a2.so we failed to do deep clone.
In my opinion , serialize and unserialize is a good way of making deep clone,but sometimes we dont
want to clone too deep,as the example I show above.