Reputation: 4204
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!
Upvotes: 1
Views: 50
Reputation: 8577
Since it's a stdClass, you could cast to array, then loop over that.
e.g.,
public function __construct(stdClass $row = null)
{
if ($row) {
$row = (array)$row;
foreach ($row as $key => $val) {
$this->$key = $val;
}
}
}
Upvotes: 3