简体   繁体   中英

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

I have a User class with subclasses like Parent and Student . In the constructor, I want to pass a stdObject and set each property to the same-named property in my object.

Here's what I have now:

     /**
     * 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;
        }
    }

Instead of if(isset()) 's for each property, could I use a foreach($row as $key => $value){ and then set $this->$key=$value ? Or does this only work for arrays?

If that does work, can I access properties using both object -> notation and array [] notation?

Thanks in advance!

Since it's a stdClass, you could cast to array, then loop over that.

eg,

public function __construct(stdClass $row = null)
{
    if ($row) {
        $row = (array)$row;
        foreach ($row as $key => $val) {
            $this->$key = $val;
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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