Page 1 of 1

Change object's class to an inherited one

Posted: Sat May 31, 2008 8:19 am
by anjanesh
I need to change an object's class to an inherited one.

Code: Select all

<?php
class Contact
{
        public $Name;
 
        public function foo_contact()
        {
                echo "Contact\n";
        }
 
        public function changeClass($className)
        {
                /*
                $this.__CLASS__ = $className;
                */
 
                $o = new $className;
                $o = clone $this;
                // $this = $o;
        }
 
        public function __clone()
        {
        }
}
 
class Customer extends Contact
{
        public $StoreVisits;
 
        public function foo_customer()
        {
                echo "Customer\n";
        }
 
}
 
class Supplier extends Contact
{
        public $SupplierID;
 
        public function foo_supplier()
        {
                echo "Supplier\n";
        }
}
 
$c = new Contact();
$c->Name = 'John';
 
/*
After some lines, I perform operations that are specific to Customer or Supplier
*/
 
$c->changeClass('Customer'); // How do I change it to an instance of a Customer ?
echo $c->Name."\n"; // Should print John
$c->StoreVisits = 5;
$c->foo_customer();
?>
Is there a way to change its class. I thought this should be possible because we're retaining the parent's properties.

Thanks

Re: Change object's class to an inherited one

Posted: Sat May 31, 2008 8:29 am
by Ambush Commander
What you want, I believe, is the State pattern. Alternative interfaces can be managed using __call()