Jump to content

PaulBain

New Members
  • Posts

    2
  • Joined

  • Last visited

    Never

Profile Information

  • Gender
    Not Telling

PaulBain's Achievements

Newbie

Newbie (1/5)

0

Reputation

  1. 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.
  2. 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 run apple 2nd run pear pear 3rd run grapes grapes grapes etc.. Any help much appreciated.
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.