How to convert (cast) Object to Array without Class Name prefix in PHP?

后端 未结 4 632
被撕碎了的回忆
被撕碎了的回忆 2021-02-10 11:16

How to convert (cast) Object to Array without Class Name prefix in PHP?

class Teste{

    private $a;
    private $b;

    function __construct($a, $b) {
                


        
4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-10 11:48

    As far as I know, PHP doesn't have a simple way to do what you want. Most languages don't. You should look into reflection. Take a look at this document: http://www.php.net/manual/en/reflectionclass.getproperties.php

    I've made a function that should work as expected:

    function objectToArr($obj)
    {
        $result = array();
        ReflectionClass $cls = new ReflectionClass($obj);
        $props = $cls->getProperties();
        foreach ($props as $prop)
        {
            $result[$prop->getName()] = $prop->getValue($obj);
        }
    }
    

提交回复
热议问题