I have object properties in my code that look like this:
$obj ->field_name_cars; $obj ->field_name_clothes;
The problem is I have 100s of field names and need to write the property name dynamically. Otherwise, the object name and the keys for the property will always be the same. So I tried:
$obj -> $field;
Hoping that the name of the property would dynamically be changed and access the correct values. But, I keep getting 'undefined property $field in stdClass::$field;
More or less I am trying dynamically write the php before it executes so that it can output the proper values. Thoughts on how to approach this?
Update for PHP 7.0
PHP 7 introduced changes to how indirect variables and properties are handled at the parser level (see the corresponding RFC for more details). This brings actual behavior closer to expected, and means that in this case
$obj->$fieldwill produce the expected result.
In cases where the (now improved) default behavior is undesired, curly braces can still be used to override it as shown below.
Write the access like this:
This "enclose with braces" trick is useful in PHP whenever there is ambiguity due to variable variables.
Consider the initial code
$obj->$field-- does this mean "access the property whose name is given in
$field", or "access the element with key
0of the property whose name is given in
$field"? The braces allow you to be explicit.