Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php object : get value of attribute by computed name

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?

like image 896
groovehunter Avatar asked Mar 29 '10 09:03

groovehunter


People also ask

How do you access the properties of an object in PHP?

The most practical approach is simply to cast the object you are interested in back into an array, which will allow you to access the properties: $a = array('123' => '123', '123foo' => '123foo'); $o = (object)$a; $a = (array)$o; echo $o->{'123'}; // error!

How get the key of an object in PHP?

To display only the keys from an object, use array_keys() in PHP.

How to access class properties in PHP?

Within class methods non-static properties may be accessed by using -> (Object Operator): $this->property (where property is the name of the property). Static properties are accessed by using the :: (Double Colon): self::$property .

What is an object PHP?

Definition and Usage In PHP, Object is a compound data type (along with arrays). Values of more than one types can be stored together in a single variable. Object is an instance of either a built-in or user defined class. In addition to properties, class defines functionality associated with data.


2 Answers

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};
like image 137
Nicolò Martini Avatar answered Oct 04 '22 22:10

Nicolò Martini


$myobject->{'field_'.$key}
like image 35
Ignacio Vazquez-Abrams Avatar answered Oct 04 '22 20:10

Ignacio Vazquez-Abrams