5

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?

5 Answers 5

9

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};
Sign up to request clarification or add additional context in comments.

Comments

8
$myobject->{'field_'.$key}

2 Comments

+1 - you can use curly braces {} whenever you want PHP to evaluate their contents before the rest of the expression
Hello, Can I use something like this $myObject->{'level1->level2'}.. Or $myObject->{level1}->{level2}. How can I do it for multiple levels, when the level-values are dynamic?
1
$val = $myobject->$myattr;

Comments

1

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.

Comments

1

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

$myObj->__get($myAttr)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.