php object : get value of attribute by computed name
How 开发者_JAVA技巧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?
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};
$myobject->{'field_'.$key}
$val = $myobject->$myattr;
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.
I know this is an old subject, but why not just use magic methods?
$myObj->__get($myAttr)
精彩评论