2012-01-10 11 views
0

SOAPサービスの場合、同じタイプのネストされたオブジェクトの任意の数を持つことができるオブジェクトを生成する必要があります。私が思いついた唯一の実用的な解決策はevalを使った解決策でした。実際には、$ nestedObjArrayのオブジェクトはかなり大きくなっています。以下の3文を生成し動的ネストされたオブジェクトに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];'); 
} 

$finalObj->nested = $nestedObjArray[0]; 
$finalObj->nested->nested = $nestedObjArray[1]; 
$finalObj->nested->nested->nested = $nestedObjArray[2]; 

これはうまく動作しますが、かなり醜いです。誰かがよりエレガントなソリューションを考えることができますか?ところで、次の代わりにevalラインが動作しません:

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

答えて

1

あなたが本当に何をすべきが指す別の変数を保持している。この程度

+0

はい、明らかにこれが最適な解決策です。私は自分自身を試した最初の解決策であると私は誓っていたかもしれません。どういうわけか私は$ innerObjを自分自身で上書きし続けました。私は寝る必要があると思う。ありがとうございました。 – Bas

1

何本使って参照変数

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

変数によってproberty用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; 
} 

、あるいはあなたがそれらの行の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]; 
} 
1

何内部オブジェクト。たとえば...

$finalObj = new stdClass(); 
$innerObj = $finalObj; 
for($i = 0; $i < count($nestedObjArray); $i++) { 
    $innerObj->nested = $nestedObjArray[$i]; 
    $innerObj = $innerObj->nested; 
} 
関連する問題