views:

136

answers:

4

hi simple question -

How do I access an attribute of an object by name, if i compute the name at runtime?

Ie. 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!!

TIA florian

+6  A: 
$myobject->{'field_'.$key}
Ignacio Vazquez-Abrams
+1 - you can use curly braces `{}` whenever you want PHP to evaluate their contents before the rest of the expression
Andy
+1  A: 
$val = $myobject->$myattr;
Geexbox
+1  A: 

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};
Nicolò Martini
A: 

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.

Davide Gualano