Change object's class to an inherited one

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
anjanesh
DevNet Resident
Posts: 1679
Joined: Sat Dec 06, 2003 9:52 pm
Location: Mumbai, India

Change object's class to an inherited one

Post 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
User avatar
Ambush Commander
DevNet Master
Posts: 3698
Joined: Mon Oct 25, 2004 9:29 pm
Location: New Jersey, US

Re: Change object's class to an inherited one

Post by Ambush Commander »

What you want, I believe, is the State pattern. Alternative interfaces can be managed using __call()
Post Reply