Return variable from within object like array
A rather cryptic title, but it's difficult to phrase.
Say I have an object from mysql_fetch_object()
. I want to use a getter to return a value from a column.
For example, in a class, we have $this->data
. How can I return say $this->data->id
(ID column from table) using an argument from the getter function.
This won't work, but somethi开发者_如何学Pythonng along the lines of:
public function data($key)
{
return $this->data[$key];
}
Thanks for any help.
what about return $this->data->$key
?
or if you implement ArrayAccess, return $this->data->$key from the offsetGet() function, then you can use $object[$key] to retrieve the data
I think what you're searching for are variable variables.
But using mysql_fetch_assoc
might be better suited for what you want to do.
Maybe your looking for __get method ? http://php.net/manual/en/language.oop5.overloading.php Not really sure about what you're looking for.
something like.
public function __get($name) {
if (array_key_exists($name, $this->data)) {
return $this->data[$name];
}
return null;
}
Now you can access your data as $obj->key
精彩评论