[英]Using eval for dynamic nested objects
For a SOAP service I have to generate an object, which can have an arbitrary number of nested objects of the same type. 对于SOAP服务,我必须生成一个对象,该对象可以具有任意数量的相同类型的嵌套对象。 The only working solution I have come up with was one using eval.
我想出的唯一可行的解决方案是使用eval的解决方案。 I have simplified the code somewhat, in reality the objects in the $nestedObjArray are considerably larger.
我已经简化了代码,实际上$ 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];');
}
Which generates the following 3 statements: 生成以下3条语句:
$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];
what about this using reference variable 那使用参考变量呢
$finalObj = new stdClass();
$addToObject = $finalObj;
for ($i = 0; $i < count( $nestedObjArray ); $i ++) {
$addToObject->nested = $nestedObjArray[$i];
$addToObject = $addToObject->nested;
}
PS Correct syntax for proberty by variable is $finalObj->nested->{$nestedStr}
PS正确按变量探查的语法为
$finalObj->nested->{$nestedStr}
PPS I just wonder what purpose of this ? PPS我只是想知道这是什么目的?
What about this: 那这个呢:
$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;
}
Or even if you want to remove 2 of those lines, this: 或者,即使您要删除其中两行,也可以这样做:
$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];
}
What you really should do is keep a separate variable that points to the inner object. 您真正应该做的是保留一个单独的变量,该变量指向内部对象。 For instance...
例如...
$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.