How to Cast Objects in PHP

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

    You may think about factories

    class XyFactory {
        public function createXyObject ($other) {
            $new = new XyObject($other->someValue);
            // Do other things, that let $new look like $other (except the used class)
            return $new;
        }
    }
    

    Otherwise user250120s solution is the only one, which comes close to class casting.

提交回复
热议问题