簡體   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