4

我可以得到帮助以了解这是否可能吗?

我想动态选择数组。

例如,

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

非常感谢。

4

2 回答 2

3

您可以按路径分解路径->并逐段跟踪对象:

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"
于 2013-11-14T23:48:06.887 回答
2

简短的回答:没有。

长答案:

您可能正在寻找参考资料吗?好吧,可能不是。

无论如何,您最好编写自己的一组类或函数,例如:

setUsingPath($oj, 'A->B->C->D', $x);
$x = getUsingPath($oj, $E);

但是,如果您确定您想要的是(未指定)问题的最佳解决方案并且是要使用的语法,那么使用shudder magic methods$E = 'A->B'; $oj->E...应该是可能的。一组递归的shudder应该可以解决问题。 __get()

于 2013-11-15T00:28:01.137 回答