Home » PHP » PHP_Compat » Bug #7519
clone does not return reference
Details
| Submitted | 2006-04-28 16:54 UTC |
|---|---|
| From | ben at benjaminku dot com |
| Status | Wont fix |
| Package | PHP_Compat |
| PHP Version | 4.3.11 |
| OS | Mac OS X 10.4 |
| Roadmaps | (Not assigned) |
Comments
[2006-04-28 16:54 UTC] ben at benjaminku dot com
Description:
------------
even if code is executed in the __clone method (say, re-
linking new cloned child objects), it breaks when trying to
assign to a new variable.
For example, I have child objects that link back to the
parent, so when I clone an object, I have the following
__clone method:
function __clone() {
parent::__clone();
$this->child =& clone($this->child);
$this->child->parent =& $this;
}
This does not work for the resulting new_object's child is
linked to the original cloned object and PHP 4 creates an
additional copy of this object which when referenced, is
different from the original object.
Test script:
---------------
I have found a solution that seems to fix this issue:
Change:
function clone($object)
To:
function &clone($object)
This allows you to get the object modified by the __clone method back.
$new_obj =& clone($original);
[2006-12-14 13:53 UTC] ben at benjaminku dot com
what's arpad?
The workaround described should give the desired
functionality, otherwise, you are essentially making 2 copies
of the object, one inside the function, and another during the
assignment to the variable. However, if we want to be able to
use constructors and initializers using the __clone()
function, we need to be able to get a handle to the instance
of the object created by clone() and not just a copy of it.
[2006-12-14 13:54 UTC] ben at benjaminku dot com
oh, and what's phpt?
[2007-04-06 17:14 UTC] ben at benjaminku dot com
yes, unfortunately, because of something in PHP5, I don't
think it's possible to have code that works in PHP 4 and 5 for
this kind of complex object-reference mapping. I had to strip
out all the &$variable and =& from my code to get the
relationships to work right under PHP5.