Convert a PHP object to an associative array

后端 未结 30 2229
走了就别回头了
走了就别回头了 2020-11-22 02:18

I\'m integrating an API to my website which works with data stored in objects while my code is written using arrays.

I\'d like a quick-and-dirty function to convert

30条回答
  •  傲寒
    傲寒 (楼主)
    2020-11-22 02:48

    class Test{
        const A = 1;
        public $b = 'two';
        private $c = test::A;
    
        public function __toArray(){
            return call_user_func('get_object_vars', $this);
        }
    }
    
    $my_test = new Test();
    var_dump((array)$my_test);
    var_dump($my_test->__toArray());
    

    Output

    array(2) {
        ["b"]=>
        string(3) "two"
        ["Testc"]=>
        int(1)
    }
    array(1) {
        ["b"]=>
        string(3) "two"
    }
    

提交回复
热议问题