如何从stdClass对象中正确创建自己的对象

时间:2015-06-09 08:58:31

标签: php constructor dynamic-binding

我根据从API响应中获得的数据创建人员实例。

数据以\ stdClass形式返回,我想将其转换为我自己的对象。 有没有办法在构造函数中传递所有调用并使其更优雅?

Class Person 
{
   protected $Name;
   protected $Email;
   ...
   protected $Property40;

   **// Is there an elegant way to do it? Assuming I know all the  property names**
   public function __construct(\stdClass $person) 
   {
      $this->Name       = $person->Name;
      $this->EMail      = $person->EMail;
      ...
      $this->Property40 = $person->Property40
   }

}

TNX

1 个答案:

答案 0 :(得分:1)

public function __construct(\stdClass $person) 
{
    foreach ($person as $attr => $val) {
       $this->$attr = $val;
    }
}