php object : get value of attribute by computed name

*爱你&永不变心* 提交于 2019-12-07 10:08:29

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!