>我可以得到帮助以了解这是否可能吗?
我想动态选择数组。
例如
$oj = (object)['A' => (object)['B' => (object)['C' => (object)['D' => []]]]]
$E = 'A'
$oj->$E // this will work
$E = 'A->B'
$oj->$E // this will not work
除了编写完整路径之外,我还能做什么?或者也许请告诉我这是否可能,或者是否有任何我可以参考的例子?
$oj[A][B][C][D] <---NO
$oj->A->B->C->D <---NO
$E = A->B->C->D
$oj->E <--What I want
Question Update:
$oj->E = 'Store something' <-What I want, then will store into $oj.
//So E here is not pick up the value of D, but the path of D;
谢谢。
您可以通过->
分解路径并逐部分路径跟踪对象:
function getPath($obj,$path) {
foreach(explode('->',$path) as $part) $obj = $obj->$part;
return $obj;
}
例
$oj = (object)['A' => (object)['B' => (object)['C' => (object)['D' => []]]]];
$E = 'A->B->C->D';
getPath($oj,$E);
如果你也想写,你可以用eval
做丑陋但简单的方法:
eval("'$tgt=&'$oj->$E;"); // $tgt is the adress of $oj->A->B->C->D->E
print_r($tgt); // original value of $oj->A->B->C->D->E
$tgt = "foo";
print_r($oj); // $oj->A->B->C->D->E = "foo"
简短回答:不。
长答案:
您是否可能正在寻找参考资料?好吧,可能不是。
在任何情况下,你最好编写自己的类或函数集,例如:
setUsingPath($oj, 'A->B->C->D', $x);
$x = getUsingPath($oj, $E);
但是,如果您确定您想要的是(未指定)问题的最佳解决方案,并且$E = 'A->B'; $oj->E...
语法是可用的,那么使用颤抖魔术方法应该是可能的。一组递归颤抖__get()
应该可以解决问题。