繁体   English   中英

我如何迭代这些对象属性并在PHP中相应地设置它们?

[英]How can I iterate over these object properties and set them accordingly in PHP?

我有一个User类,其子类如ParentStudent 在构造函数中,我想传递一个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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM