|
Posted by Kevin on 08/26/05 23:50
Hi all,
I've got a PHP4 app that I developed which I'm trying to get to run on a
PHP5 server. Everything works great, except for one thing.
There's a particular routine that creates an original object, then copies
it. (The object constructor gets some meta information from the database, so
I copy it for performance reasons). The routine then modifies the copies.
PHP5 copies by reference by default, so this doesn't work--- I'm not
modifying the copies, I'm modifying the original. I read about a trick to
create a PHP4/PHP5 compatible clone function, but that doesn't work either.
PHP5's clone is a shallow copy, so the properties of the original which are
other objects only get referenced.
// Start Example:
class simple
{
var $key;
function simple()
{}
}
class cloneable
{
var $simple;
function cloneable()
{
$this->simple = new simple();
}
}
$prototype = new cloneable();
$record1 = clone($prototype);
$record1->simple->key='blue';
$record2 = clone($prototype);
$record2->simple->key='red';
echo $record1->simple->key;
echo $record2->simple->key;
// End example
In PHP4 (assume that the clone function has been defined to just return a
copy of the original object) this code outputs "bluered". In PHP5 it
outputs "redred".
How do I deep copy an object in PHP5 the way PHP4's assignment operator
works?
TIA,
Kevin
Navigation:
[Reply to this message]
|