Jump to content


Photo

PHP Objects Clone and Arrays not working [SOLVED]


  • Please log in to reply
1 reply to this topic

#1 PaulBain

PaulBain
  • New Members
  • Pip
  • Newbie
  • 2 posts

Posted 28 July 2006 - 10:32 AM

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:

foreach($rows as $id=>$row) {
	$do = new $this->_doname;
	$do->_data=$row;
	$do->load($id);
	$this->_dataobjects[] = $do;
}

I changed this to:

$temp = new $this->_doname;
foreach($rows as $id=>$row) {
	$do = clone $temp;
	$do->_data=$row;
	$do->load($id);
	$this->_dataobjects[] = $do;
}

However when I create a collection, all the dataobjects in the the array are the same.
I have tried :
$this->_dataobjects[] = clone $do;

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.

#2 PaulBain

PaulBain
  • New Members
  • Pip
  • Newbie
  • 2 posts

Posted 28 July 2006 - 12:13 PM

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:

$temp = new $this->_doname;

 foreach($rows as $id=>$row) {
         $do = clone $temp;
         $do->_data=$row;
         $do->load($id);
         $this->_dataobjects[]= $this->copy($do);
 }

with the copy function:



public function copy($do)
 {
    $do = serialize($do);
    return unserialize($do);
 }



Note. Clone is still needed to prevent the origional template object from
being overwritten.






0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users