For a SOAP service I have to generate an object, which can have an arbitrary number of nested objects of the same type. The only working solution I have come up with was one using eval. I have simplified the code somewhat, in reality the objects in the $nestedObjArray are considerably larger.
$nestedObjArray = array();
$nestedObjArray[] = new stdClass();
$nestedObjArray[] = new stdClass();
$nestedObjArray[] = new stdClass();
$finalObj = new stdClass();
for ($i = 0; $i < count($nestedObjArray); $i++) {
$nestedStr = str_repeat("->nested", $i);
eval('$finalObj->nested'.$nestedStr.' = $nestedObjArray[$i];');
}
Which generates the following 3 statements:
$finalObj->nested = $nestedObjArray[0];
$finalObj->nested->nested = $nestedObjArray[1];
$finalObj->nested->nested->nested = $nestedObjArray[2];
This works fine, but is pretty ugly. Can anyone think of a more elegant solution? Btw, the following instead of the eval line doesn't work:
$finalObj->nested{$nestedStr} = $nestedObjArray[$i];