List Info

Thread: note 78364 added to language.oop5.cloning




note 78364 added to language.oop5.cloning
user name
2007-10-08 09:43:02
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/78364
Del: integrated  -- h
ttps://master.php.net/note/delete/78364/integrated
Del: useless     -- http
s://master.php.net/note/delete/78364/useless
Del: bad code    -- htt
ps://master.php.net/note/delete/78364/bad+code
Del: spam        -- https:/
/master.php.net/note/delete/78364/spam
Del: non-english -- 
https://master.php.net/note/delete/78364/non-english
Del: in docs     -- http
s://master.php.net/note/delete/78364/in+docs
Del: other reasons-- https://mast
er.php.net/note/delete/78364
Reject      -- https://mast
er.php.net/note/reject/78364
Search      -- https://
master.php.net/manage/user-notes.php

-- 
PHP Notes Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub
.php


[1]

about | contact  Other archives ( Real Estate discussion Medical topics )