Php object: get attribute value by computed name

How to access an attribute of an object by name if I calculated the name at runtime?

For instance. I "field_" . $key over the keys and want to get each value of the "field_" . $key attributes "field_" . $key "field_" . $key .

There is getattribute(myobject, attrname) in python getattribute(myobject, attrname) .

It works, of course, with eval("$val=$myobject->".$myattr.";"); but IMO is ugly - is there a cleaner way to do this?

+4
source share
5 answers

Remember that a very powerful PHP function is Variables.

you can use

 $attr = 'field' . $key; $myobject->$attr; 

or more concisely using parentheses

 $myobject->{'field_'.$key}; 
+8
source
 $myobject->{'field_'.$key} 
+8
source
 $val = $myobject->$myattr; 
+1
source

With reflection :

 $reflectedObject = new ReflectionObject($myobject); $reflectedProperty = $reflectedObject->getProperty($attrName); $value = $reflectedProperty->getValue($myobject); 

This only works if the available property is public, if it is protected or the exception is closed.

+1
source

I know this is an old question, but why not just use magic methods?

 $myObj->__get($myAttr) 
+1
source

Source: https://habr.com/ru/post/1305441/


All Articles