2012-01-10 148 views
0

對於SOAP服務,我必須生成一個對象,該對象可以有任意數量的相同類型的嵌套對象。我提出的唯一工作解決方案是使用eval。我有點簡化了代碼,實際上$ nestedObjArray中的對象相當大。對動態嵌套對象使用eval

$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]; 

這工作得很好,但很醜陋。任何人都可以想到更優雅的解決方案嗎?順便說一句,下面,而不是EVAL行不起作用:

$finalObj->nested{$nestedStr} = $nestedObjArray[$i]; 

回答

1

你真的應該做的是保持一個獨立的變量指向內部對象。例如...

$finalObj = new stdClass(); 
$innerObj = $finalObj; 
for($i = 0; $i < count($nestedObjArray); $i++) { 
    $innerObj->nested = $nestedObjArray[$i]; 
    $innerObj = $innerObj->nested; 
} 
+0

是的,顯然這是最好的解決方案。我可以發誓這是我自己也嘗試的第一個解決方案。不知何故,我一直覆蓋$ innerObj自己。我想我需要一些睡眠。謝謝。 – Bas 2012-01-10 18:57:45

1

這個怎麼使用引用變量

$finalObj = new stdClass(); 
$addToObject = $finalObj; 
for ($i = 0; $i < count($nestedObjArray); $i ++) { 
    $addToObject->nested = $nestedObjArray[$i]; 
    $addToObject = $addToObject->nested; 
} 

PS正確語法可變proberty是$finalObj->nested->{$nestedStr}

PPS我只是想知道這是什麼目的?

1

這個什麼:

$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; 
} 

或者即使你想刪除這些行2,本:

$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]; 
}