note 68604 deleted from language.oop5.cloning by danielc
| From: | danielc@php.net | Date: | Sun, 27 Jul 2008 05:31:25 +0000 |
| Subject: | note 68604 deleted from language.oop5.cloning by danielc | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-142802@lists.php.net to get a copy of this message | ||
Note Submitter: paul at accessdesigns dot org dot uk
Reason: 2
----
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