问题
How do I access an attribute of an object by name, if I compute the name at runtime?
For instance. I loop over keys and want to get each value of the attributes "field_" . $key
.
In python there is getattribute(myobject, attrname)
.
It works, of course, with eval("$val=$myobject->".$myattr.";");
but IMO this is ugly - is there a cleaner way to do it?
回答1:
Keep always in mind that a very powerful feature of PHP is its Variable Variables
You can use
$attr = 'field' . $key;
$myobject->$attr;
or more concisely, using curl brackets
$myobject->{'field_'.$key};
回答2:
$myobject->{'field_'.$key}
回答3:
$val = $myobject->$myattr;
回答4:
With reflection:
$reflectedObject = new ReflectionObject($myobject);
$reflectedProperty = $reflectedObject->getProperty($attrName);
$value = $reflectedProperty->getValue($myobject);
This works only if the accessed property is public, if it's protected or private an exception will occurr.
回答5:
I know this is an old subject, but why not just use magic methods?
$myObj->__get($myAttr)
来源:https://stackoverflow.com/questions/2537028/php-object-get-value-of-attribute-by-computed-name