New class is a subclass of the original object
It needs to be php4 compatible
views:
911answers:
5I would imagine you would have to invent some sort of a "copy constructor". Then you would just create a new subclass object whilst passing in the original object.
The best method would be to create a clone method on the Subclass so that you could do:
$myvar = $subclass->clone($originalObject)
Alternatively it sounds like you could look into the decorator pattern php example
You could have your classes instantiated empty and then loaded by any number of methods. One of these methods could accept an instance of the parent class as an argument, and then copy its data from there
class childClass extends parentClass
{
function childClass()
{
//do nothing
}
function loadFromParentObj( $parentObj )
{
$this->a = $parentObj->a;
$this->b = $parentObj->b;
$this->c = $parentObj->c;
}
};
$myParent = new parentClass();
$myChild = new childClass();
$myChild->loadFromParentObj( $myParent );
A php object isn't a whole lot different to an array, and since all PHP 4 object variables are public, you can do some messy stuff like this:
function clone($object, $class)
{
$new = new $class();
foreach ($object as $key => $value)
{
$new->$key = $value;
}
return $new;
}
$mySubclassObject = clone($myObject, 'mySubclass');
Its not pretty, and its certianly not what I'd consider to be good practice, but it is reusable, and it is pretty neat.
You can do it with some black magic, although I would seriously question why you have this requirement in the first place. It suggests that there is something severely wrong with your design.
Nonetheless:
function change_class($object, $new_class) {
preg_match('~^O:[0-9]+:"[^"]+":(.+)$~', serialize($object), $matches);
return unserialize(sprintf('O:%s:"%s":%s', strlen($new_class), $new_class, $matches[1]));
}
This is subject to the same limitations as serialize in general, which means that references to other objects or resources are lost.