note 78363 added to language.oop5.cloning
| From: | muratyaman at gmail dot com | Date: | Mon, 08 Oct 2007 14:42:28 +0000 |
| Subject: | note 78363 added to language.oop5.cloning | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-131231@lists.php.net to get a copy of this message | ||
I think this is a bit awkward:
<?php
class A{
public $aaa;
}
class B{
public $a;
public $bbb;
function __clone(){
$this->a = clone $this->a;//clone MANUALLY!!!
}
}
$b1 = new B();
$b1->a = new A();
$b1->a->aaa = 111;
$b1->bbb = 1;
$b2 = clone $b1;
$b2->a->aaa = 222;//BEWARE!!
$b2->bbb = 2;//no problem on basic types
var_dump($b1); echo '<br />';
var_dump($b2);
/*
OUTPUT BEFORE implementing the function __clone()
object(B)#2 (3) { ["a"]=> object(A)#3 (1) { ["aaa"]=> int(222) }
["bbb"]=> int(1) }
object(B)#4 (3) { ["a"]=> object(A)#3 (1) { ["aaa"]=> int(222) }
["bbb"]=> int(2) }
OUTPUT AFTER implementing the function __clone()
object(B)#1 (3) { ["a"]=> object(A)#2 (1) { ["aaa"]=> int(111) }
["bbb"]=> int(1) }
object(B)#3 (3) { ["a"]=> object(A)#4 (1) { ["aaa"]=> int(222) }
["bbb"]=> int(2) }
*/
?>
Whenever we use another class inside, we must clone it manually. If you have 10s of classes related,
this is rather tedious. I don't want to even think about classes dynamically populated with
other objects. Be careful when designing your classes! You should look after your objects all the
time! This major change on PHP5 vs PHP4 regarding "references" definitely has very good
performance improvements but comes with very dangerous side effects as well..
----
Server IP: 194.145.210.4
Probable Submitter: 82.144.250.86
----
Manual Page -- http://www.php.net/manual/en/language.oop5.cloning.php
Edit -- https://master.php.net/note/edit/78363
Del: integrated -- https://master.php.net/note/delete/78363/integrated
Del: useless -- https://master.php.net/note/delete/78363/useless
Del: bad code -- https://master.php.net/note/delete/78363/bad+code
Del: spam -- https://master.php.net/note/delete/78363/spam
Del: non-english -- https://master.php.net/note/delete/78363/non-english
Del: in docs -- https://master.php.net/note/delete/78363/in+docs
Del: other reasons-- https://master.php.net/note/delete/78363
Reject -- https://master.php.net/note/reject/78363
Search -- https://master.php.net/manage/user-notes.php