How to Cast Objects in PHP

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

    PHP provides a very simple way of doing this by using:

    (object) ['id'=>1,'name'=>'cat']
    

    https://www.php.net/manual/en/language.types.object.php

    In your case you try this:

    $dog = json_encode($dog);
    
    $cat = (object) json_decode($dog)
    

提交回复
热议问题