Re: Change Object Type

From: Date: Mon, 25 Apr 2005 14:45:28 +0000
Subject: Re: Change Object Type
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-213809@lists.php.net to get a copy of this message
marc serra wrote:
hi, i'm looking for a solution to change the object's class. i got a class and a derived class like this: (just for example, completly stupid ^^) class Ex{ var a; var b; } class Ex2 extends Ex{ var c; } i want to create an object Ex and after change the object class to Ex2 to complete him like this: $ex = new Ex(); $ex->a = 1; $ex->b = 2;
$ex2 = (Ex2)$ex;      /// here i want to convert object Ex to object Ex2
$ex2->c = 5; Can someone help me? I know it's possible to do this in JAVA but it is possible to do the same in PHP ?
its not possible exactly how you propose it, but I can certainly see a way of doing it , something like (just an idea - code is not tested): class Ex {
    function __contruct($extend = null)
    {
if (is_object($extend)) {
	    $parents = parent_classes($this);
	    if (in_array(get_class($extend, $parents))) {
// is a parent! // now do some kind of loop to set the vars
		// of $this to the values of the same vars in $extend      	
// maybe reflection would a good way to write this // generically
            }
}
    }
    var a;
    var b;
} class Ex2 extends Ex {
    var c;
} $A = new Ex(); $A->a = 1; $A->b = 2; $B = new Ex2( $ex ); $B->c = 5; also you might want to look into writing a custom __clone() method for the relevant class which returns a different (subclass) object underwhatever circumstances (I have no idea whether it is allowed to return an object from __clone() of a different class to the class of the object you are cloning)
thx in advance, Marc.


« previous php.general (#213809) next »