1

We have a system where we have reason to instantiate an object before we know what its specific type is. For example, we wish to instantiate a class "media" before we know whether the final class will be "book" or "cd".

Here is what we are doing. We instantiate the "media" object, and once we know what type of media it is, we instantiate a "book", passing in the media object.

class Book extends Media
{
    public function __construct( $parent )
    {
        $vars = get_object_vars( $parent );

        foreach( $vars as $key => $value )
            $this->$key = $value;
    }   
}

//elsewhere
$item = new Media();
$item->setPrice( $price );
//other code, figure out the item type
$item = new Book( $item );

Is there a better way to do something like this? Is this dynamic polymorphism?

Karptonite
  • 1,490
  • 2
  • 14
  • 30
  • 1
    Have you looked into [this post](http://stackoverflow.com/questions/3243900/convert-cast-an-stdclass-object-to-another-class)? – Roberto Jun 05 '12 at 04:02
  • I hadn't seen that. The second response, using Reflection, looks intriguing. – Karptonite Jun 05 '12 at 17:39

1 Answers1

0

In case u really can't determine what type of object is i can recommend u factory pattern. With this pattern u has only one entry point and this helps u to get yr code simpler and 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 as properties

        public function setParamsFromObject($object)
        {
            $vars = get_object_vars($object);
            foreach ($vars as $key => $value) {
                $this->$key = $value;
            }

            return $this;
        }
    }

$media = new Media;
$media->setParams($params)
// some stuff
//...
$book = ObjectFactory::factory($media, $objectType);
mrsombre
  • 43
  • 3