Changing an object's type after it has been instantiated in PHP -


we have system have reason instantiate object before know specific type is. example, wish instantiate class "media" before know whether final class "book" or "cd".

here doing. instantiate "media" object, , once know type of media is, instantiate "book", passing in media object.

class book extends media {     public function __construct( $parent )     {         $vars = get_object_vars( $parent );          foreach( $vars $key => $value )             $this->$key = $value;     }    }  //elsewhere $item = new media(); $item->setprice( $price ); //other code, figure out item type $item = new book( $item ); 

is there better way this? dynamic polymorphism?

in case u can't determine type of object can recommend u factory pattern. pattern u has 1 entry point , helps u yr code simpler , readable.

short example:

    class objectfactory {         public static function factory($object, $objecttype)         {             $result = false;              switch ($objecttype) {                 case 'book':                     $result = new book;                     $result->setparams($object->getparams());                     break;                  case 'othertype':                     $result = new othertype;                     $result->setparams($object->getparams());                     // or                     $result->setparamsfromobject($object);                     break;                     ... //etc             }             return $result;         }     }      class book extends mediaabstract     {         public function __set($name, $value)         {             $this->_params($name, $value);         }          public function __get($name)         {             return $this->_params[$value];         }          public function setparams(array $params)         {             $this->_params = $params;             return $this;         }          public function getparams()         {             return $this->_params;         }          // in case u want store params properties          public function setparamsfromobject($object)         {             $vars = get_object_vars($object);             foreach ($vars $key => $value) {                 $this->$key = $value;             }              return $this;         }     }  $media = new media; $media->setparams($params) // stuff //... $book = objectfactory::factory($media, $objecttype); 

Comments

Popular posts from this blog

java - Play! framework 2.0: How to display multiple image? -

gmail - Is there any documentation for read-only access to the Google Contacts API? -

php - Controller/JToolBar not working in Joomla 2.5 -