How to convert an array to object in PHP?

前端 未结 30 2838
说谎
说谎 2020-11-22 02:48

How can I convert an array like this to an object?

[128] => Array
    (
        [status] => "Figure A.
 Facebook\'s horizontal scrollbars showing u         


        
30条回答
  •  遇见更好的自我
    2020-11-22 03:16

    You can use Reflection:

    'maria','age'=>33];
    
    class Person {
    
        public $name;
        public $age;
    
        public function __construct(string $name, string $age){
            $this->name  = $name;
            $this->age = $age;
        }
    }
    
    function arrayToObject(array $array, string $class_name){
    
        $r = new ReflectionClass($class_name);
        $object = $r->newInstanceWithoutConstructor();
        $list = $r->getProperties();
        foreach($list as $prop){
          $prop->setAccessible(true);
          if(isset($array[$prop->name]))
            $prop->setValue($object, $array[$prop->name]);
        } 
    
        return $object;
    
    }
    
    $pessoa1 = arrayToObject($array, 'Person');
    var_dump($pessoa1);
    

提交回复
热议问题