如何从 stdClass 对象中正确创建我自己的对象
How to create my own object properly out of stdClass object
我正在根据从 API 响应中获得的数据创建人员实例。
数据 returns 为 \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
public function __construct(\stdClass $person)
{
foreach ($person as $attr => $val) {
$this->$attr = $val;
}
}
我正在根据从 API 响应中获得的数据创建人员实例。
数据 returns 为 \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
public function __construct(\stdClass $person)
{
foreach ($person as $attr => $val) {
$this->$attr = $val;
}
}