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?
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!
To display only the keys from an object, use array_keys() 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 .
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.
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};
$myobject->{'field_'.$key}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With