accessing object content within PHP works fine when you only set a single level like this:
$obj = new stdClass();
$obj->name1 = 'value1';
$param1 = 'name1';
echo $obj->$param1; // echoes values1 as expected
But what if I need deeper object content like this (w/o transforming it into an array first or similar stuff...)
$obj = new stdClass();
$obj->name1->name2 = 'value2';
$param2 = 'name1->name2';
echo $obj->$param2; // does not echo value2 obviously
How can I solve this?
First approach (simple):
$obj = new stdClass();
$obj->name1->name2 = 'value2';
$param1 = 'name1';
$param2 = 'name2';
echo $obj->$param1->$param2;
Second approach (more generalized):
$obj = new stdClass();
$obj->name1->name2 = 'value2';
$params = 'name1->name2';
$value = $obj;
foreach(preg_split("/-\>/",$params) as $param)
$value = $value->$param;
echo $value;
You could just parse the $param2
string and print out the value at the end:
$result = $obj;
foreach( explode( '->', $param2) as $var) {
$result = $result->$var;
}
echo $result;
But... I don't see why you wouldn't use an array for this.