note 116329 added to language.oop5.cloning

From: Date: Sat, 13 Dec 2014 12:54:01 +0000
Subject: note 116329 added to language.oop5.cloning
Groups: php.notes 
Request: Send a blank email to php-notes+get-201141@lists.php.net to get a copy of this message
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"; ?> ---- Server IP: 72.52.91.14 Probable Submitter: 85.179.7.49 ---- Manual Page -- http://php.net/manual/en/language.oop5.cloning.php Edit -- https://master.php.net/note/edit/116329 Del: integrated -- https://master.php.net/note/delete/116329/integrated Del: useless -- https://master.php.net/note/delete/116329/useless Del: bad code -- https://master.php.net/note/delete/116329/bad+code Del: spam -- https://master.php.net/note/delete/116329/spam Del: non-english -- https://master.php.net/note/delete/116329/non-english Del: in docs -- https://master.php.net/note/delete/116329/in+docs Del: other reasons-- https://master.php.net/note/delete/116329 Reject -- https://master.php.net/note/reject/116329 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#201141) next »