PaulBain Posted July 28, 2006 Share Posted July 28, 2006 I am having some problems with cloning data objects using PHP5.First for some background:: I have a data object which represents a tuple in a database, which contains a list of fields.When you create a DataObject it looks up the database to get the fields names, however when I'm creating a collection of these objects, this gets very costly. I have devised a way to do only one query to get all the data, but now am working on getting only one object constructor called and then cloning the object.Here is the old code:[code] foreach($rows as $id=>$row) { $do = new $this->_doname; $do->_data=$row; $do->load($id); $this->_dataobjects[] = $do;}[/code]I changed this to:[code]$temp = new $this->_doname;foreach($rows as $id=>$row) { $do = clone $temp; $do->_data=$row; $do->load($id); $this->_dataobjects[] = $do;}[/code]However when I create a collection, all the dataobjects in the the array are the same.I have tried : [code]$this->_dataobjects[] = clone $do;[/code] and unsetting $do after use, but no luck.If I print_r the _dataobjects array in the loop using for example a collection of fruit I get:1st runapple2nd runpearpear3rd rungrapesgrapesgrapesetc..Any help much appreciated. Quote Link to comment https://forums.phpfreaks.com/topic/15873-php-objects-clone-and-arrays-not-working-solved/ Share on other sites More sharing options...
PaulBain Posted July 28, 2006 Author Share Posted July 28, 2006 The solution to this was slightly more complex than I expected. Merely using the clone keyword is not sufficient as I assumed.The problem is, when you add cloned objects to an array within a loop they are still annoyingly passed by refference. So the solution is to serialize and unserialize the object and all is good:[code] $temp = new $this->_doname; foreach($rows as $id=>$row) { $do = clone $temp; $do->_data=$row; $do->load($id); $this->_dataobjects[]= $this->copy($do); }[/code] with the copy function:[code] public function copy($do) { $do = serialize($do); return unserialize($do); }[/code] Note. Clone is still needed to prevent the origional template object from being overwritten. Quote Link to comment https://forums.phpfreaks.com/topic/15873-php-objects-clone-and-arrays-not-working-solved/#findComment-65116 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.