How to Cast Objects in PHP

后端 未结 12 1967
轮回少年
轮回少年 2020-11-27 04:24

Ive some classes that share some attributes, and i would like to do something like:

$dog = (Dog) $cat;

is it possible or is there any gener

12条回答
  •  青春惊慌失措
    2020-11-27 04:45

    a better aproach:

    class Animal
    {
        private $_name = null;
    
        public function __construct($name = null)
        {
            $this->_name = $name;
        }
    
        /**
         * casts object
         * @param Animal $to
         * @return Animal
         */
        public function cast($to)
        {
            if ($to instanceof Animal) {
                $to->_name = $this->_name;
            } else {
                throw(new Exception('cant cast ' . get_class($this) . ' to ' . get_class($to)));
            return $to;
        }
    
        public function getName()
        {
            return $this->_name;
        }
    }
    
    class Cat extends Animal
    {
        private $_preferedKindOfFish = null;
    
        public function __construct($name = null, $preferedKindOfFish = null)
        {
            parent::__construct($name);
            $this->_preferedKindOfFish = $preferedKindOfFish;
        }
    
        /**
         * casts object
         * @param Animal $to
         * @return Animal
         */
        public function cast($to)
        {
            parent::cast($to);
            if ($to instanceof Cat) {
                $to->_preferedKindOfFish = $this->_preferedKindOfFish;
            }
            return $to;
        }
    
        public function getPreferedKindOfFish()
        {
            return $this->_preferedKindOfFish;
        }
    }
    
    class Dog extends Animal
    {
        private $_preferedKindOfCat = null;
    
        public function __construct($name = null, $preferedKindOfCat = null)
        {
            parent::__construct($name);
            $this->_preferedKindOfCat = $preferedKindOfCat;
        }
    
        /**
         * casts object
         * @param Animal $to
         * @return Animal
         */
        public function cast($to)
        {
            parent::cast($to);
            if ($to instanceof Dog) {
                $to->_preferedKindOfCat = $this->_preferedKindOfCat;
            }
            return $to;
        }
    
        public function getPreferedKindOfCat()
        {
            return $this->_preferedKindOfCat;
        }
    }
    
    $dogs = array(
        new Dog('snoopy', 'vegetarian'),
        new Dog('coyote', 'any'),
    );
    
    foreach ($dogs as $dog) {
        $cat = $dog->cast(new Cat());
        echo get_class($cat) . ' - ' . $cat->getName() . "\n";
    }
    

提交回复
热议问题