【问题标题】:How to create my own object properly out of stdClass object如何从 stdClass 对象中正确创建我自己的对象
【发布时间】:2015-06-09 08:58:30
【问题描述】:

我正在根据从 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

【问题讨论】:

    标签: php constructor dynamic-binding


    【解决方案1】:
    public function __construct(\stdClass $person) 
    {
        foreach ($person as $attr => $val) {
           $this->$attr = $val;
        }
    }
    

    【讨论】:

    • Tnx。如果我以前不知道属性名称。还能用吗?
    • 当然。 PHP 动态创建类属性。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多