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

后端 未结 4 645
被撕碎了的回忆
被撕碎了的回忆 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条回答
  •  余生分开走
    2021-02-10 11:55

    You can use Reflection to solve this task. But as usual this is a strong indicator that your class design is somewhat broken. However:

    function objectToArray($obj) {
        // Create a reflection object
        $refl = new ReflectionClass($obj);
    
        // Retrieve the properties and strip the ReflectionProperty objects down
        // to their values, accessing even private members.
        return array_map(function($prop) use ($obj) {
            $prop->setAccessible(true);
            return $prop->getValue($obj);
        }, $refl->getProperties());
    }
    
    // Usage:
    $arr = objectToArray( new Foo() );
    

提交回复
热议问题