[英]How can I iterate over these object properties and set them accordingly in PHP?
我有一个User
类,其子类如Parent
和Student
。 在构造函数中,我想传递一个stdObject
并将每个属性设置为我的对象中的同名属性。
这就是我现在拥有的:
/**
* Creates a new user from a row or blank.
* Creates a new user from a database row if given or an empty User object if null
*
* @param Object $row A row object the users table
*/
public function __construct(stdClass $row = null)
{
if ($row) {
if (isset($row->user_id)) $this->user_id = $row->user_id;
if (isset($row->first_name)) $this->first_name = $row->first_name;
if (isset($row->last_name)) $this->last_name = $row->last_name;
if (isset($row->phone)) $this->phone = $row->phone;
if (isset($row->email)) $this->email = $row->email;
}
}
而不是if(isset())
为每个属性,我可以使用foreach($row as $key => $value){
然后设置$this->$key=$value
? 或者这只适用于数组?
如果确实有效,我可以使用object ->
notation和array []
表示法来访问属性吗?
提前致谢!
因为它是一个stdClass,你可以转换为数组,然后循环它。
例如,
public function __construct(stdClass $row = null)
{
if ($row) {
$row = (array)$row;
foreach ($row as $key => $val) {
$this->$key = $val;
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.