[英]Using eval for dynamic nested objects
對於SOAP服務,我必須生成一個對象,該對象可以具有任意數量的相同類型的嵌套對象。 我想出的唯一可行的解決方案是使用eval的解決方案。 我已經簡化了代碼,實際上$ nestedObjArray中的對象要大得多。
$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];');
}
生成以下3條語句:
$finalObj->nested = $nestedObjArray[0];
$finalObj->nested->nested = $nestedObjArray[1];
$finalObj->nested->nested->nested = $nestedObjArray[2];
這可以正常工作,但是非常難看。 誰能想到一個更優雅的解決方案? 順便說一句,以下而不是評估行不起作用:
$finalObj->nested{$nestedStr} = $nestedObjArray[$i];
那使用參考變量呢
$finalObj = new stdClass();
$addToObject = $finalObj;
for ($i = 0; $i < count( $nestedObjArray ); $i ++) {
$addToObject->nested = $nestedObjArray[$i];
$addToObject = $addToObject->nested;
}
PS正確按變量探查的語法為$finalObj->nested->{$nestedStr}
PPS我只是想知道這是什么目的?
那這個呢:
$nestedObjArray = array();
$nestedObjArray[] = new stdClass();
$nestedObjArray[] = new stdClass();
$nestedObjArray[] = new stdClass();
$finalObj = new stdClass();
$thisObj = &$finalObj;
for ($i = 0; $i < count($nestedObjArray); $i++) {
$thisObj->nested = $nestedObjArray[$i];
$thisObj = &$thisObj->nested;
}
或者,即使您要刪除其中兩行,也可以這樣做:
$nestedObjArray = array();
$nestedObjArray[] = new stdClass();
$nestedObjArray[] = new stdClass();
$nestedObjArray[] = new stdClass();
$finalObj = new stdClass();
for ($i = 0, $thisObj = &$finalObj; $i < count($nestedObjArray); $i++, $thisObj = &$thisObj->nested) {
$thisObj->nested = $nestedObjArray[$i];
}
您真正應該做的是保留一個單獨的變量,該變量指向內部對象。 例如...
$finalObj = new stdClass();
$innerObj = $finalObj;
for($i = 0; $i < count($nestedObjArray); $i++) {
$innerObj->nested = $nestedObjArray[$i];
$innerObj = $innerObj->nested;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.