note 68604 added to language.oop5.cloning

From: Date: Thu, 03 Aug 2006 08:47:12 +0000
Subject: note 68604 added to language.oop5.cloning
Groups: php.notes 
Request: Send a blank email to php-notes+get-115507@lists.php.net to get a copy of this message
I noticed when trying to clone a series of objects in a loop and and adding them to an array, the objects were still passed by reference, so all objects took the same value as the last object cloned and added to the array. The solution was to use the copy function as below which truly clones objects. Here is an example: <?php $temp = new $this->_doname; foreach($rows as $id=>$row) { $do = clone $temp; $do->load($id); $this->_dataobjects[]= clone $do; } ?> This results in every object having the same value. However using: <?php $this->_dataobjects[]= $this->copy($do); ?> with <?php public function copy() { $serialized_contents = serialize($this); return unserialize($serialized_contents); } ?> Actually produces the expected result. Paul Bain ---- Server IP: 83.138.144.80 Probable Submitter: 195.182.4.66 ---- X-Spam-Status: No, hits=3.1 required=5.0 tests=DATE_MISSING,FROM_NO_LOWER autolearn=no version=2.64 ---- Manual Page -- http://www.php.net/manual/en/language.oop5.cloning.php Edit -- https://master.php.net/note/edit/68604 Del: integrated -- https://master.php.net/note/delete/68604/integrated Del: useless -- https://master.php.net/note/delete/68604/useless Del: bad code -- https://master.php.net/note/delete/68604/bad+code Del: spam -- https://master.php.net/note/delete/68604/spam Del: non-english -- https://master.php.net/note/delete/68604/non-english Del: in docs -- https://master.php.net/note/delete/68604/in+docs Del: other reasons-- https://master.php.net/note/delete/68604 Reject -- https://master.php.net/note/reject/68604 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#115507) next »