user658182 user658182 - 1 year ago 47
PHP Question

How do I dynamically write a PHP object property name?

I have object properties in my code that look like this:

$obj ->field_name_cars[0];
$obj ->field_name_clothes[0];

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[0];

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?

Jon Jon
Answer Source

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[0] -- does this mean "access the property whose name is given in $field[0]", or "access the element with key 0 of the property whose name is given in $field"? The braces allow you to be explicit.