Jump to content

PHP Objects Clone and Arrays not working [SOLVED]


PaulBain

Recommended Posts

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.
Link to comment
Share on other sites

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.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.