tags:

views:

911

answers:

5
  1. New class is a subclass of the original object

  2. It needs to be php4 compatible

A: 

I 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.

Joe Philllips
+1  A: 

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

Geoff
no go for PHP4, unless I implement clone myself
Azrul Rahim
+3  A: 

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 );
Jurassic_C
This is more of less my current solution. I suppose I can't expect any other magic to do this.
Azrul Rahim
+1  A: 

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.

Marc Gear
A: 

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.

troelskn