How to Cast Objects in PHP

后端 未结 12 1958
轮回少年
轮回少年 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:42

    class It {
        public $a = '';
    
        public function __construct($a) {
            $this->a = $a;
        }
        public function printIt() {
            ;
        }
    }
    
    //contains static function to 'convert' instance of parent It to sub-class instance of Thing
    
    class Thing extends it {
        public $b = '';
    
        public function __construct($a, $b) {
            $this->a = $a;
            $this->b = $b;
        }
        public function printThing() {
            echo $this->a . $this->b;
        }
            //static function housed by target class since trying to create an instance of Thing
        static function thingFromIt(It $it, $b) {
            return new Thing($it->a, $b);
        }
    }
    
    
    //create an instance of It
    $it = new It('1');
    
    //create an instance of Thing 
    $thing = Thing::thingFromIt($it, '2');
    
    
    echo 'Class for $it: ' . get_class($it);
    echo 'Class for $thing: ' . get_class($thing);
    

    Returns:

    Class for $it: It
    Class for $thing: Thing
    

提交回复
热议问题