Type casting for user defined objects

前端 未结 11 1541
没有蜡笔的小新
没有蜡笔的小新 2020-11-29 01:35

Just like we do with __ToString, is there a way to define a method for casting?

$obj = (MyClass) $another_class_obj;
11条回答
  •  [愿得一人]
    2020-11-29 01:58

    Although there's no need to type cast in PHP, you might come across a situation where you would like to convert a parent object into a child object.

    Simple

    //Example of a sub class
    class YourObject extends MyObject {
        public function __construct(MyObject $object) {
            foreach($object as $property => $value) {
                $this->$property = $value;
            }
        }
    }
    
    
    $my_object = new MyObject();
    $your_object = new YourObject($my_object);
    

    So all you do is pass the parent object down to the child object's constructor, and let the constructor copy over the properties. You can even filter / change them as needed.

    Advanced

    //Class to return standard objects
    class Factory {
        public static function getObject() {
            $object = new MyObject();
            return $object;
        }
    }
    
    //Class to return different object depending on the type property
    class SubFactory extends Factory {
        public static function getObject() {
            $object = parent::getObject();
            switch($object->type) {
            case 'yours':
                $object = new YourObject($object);
                break;
            case 'ours':
                $object = new OurObject($object);
                break;
            }
            return $object;
        }
    }
    
    //Example of a sub class
    class YourObject extends MyObject {
        public function __construct(MyObject $object) {
            foreach($object as $property => $value) {
                $this->$property = $value;
            }
        }
    }
    

    It's not type casting, but it does what you need.

提交回复
热议问题