4

May I get help to know whether this is possible?

I want to select array dynamically.

For instance,

$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

What else I can do except to write a full path? Or maybe please tell me whether this is possible or is there any example I can refer?

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

Thank you very much.

1
  • Looking for this $oj[A[B[C[D]]]] ? Commented Nov 14, 2013 at 23:29

2 Answers 2

3

You can explode the path by -> and trace the object part by part of the path:

function getPath($obj,$path) {
  foreach(explode('->',$path) as $part) $obj = $obj->$part;
  return $obj;
}

Example

$oj = (object)['A' => (object)['B' => (object)['C' => (object)['D' => []]]]];
$E = 'A->B->C->D';
getPath($oj,$E);

If you also want to write, you can do it ugly, but simple way using 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"
Sign up to request clarification or add additional context in comments.

1 Comment

thank you very much, question updated, your example will only pick up the value of D, and what I want is selecting the path
2

Short answer: No.

Long answer:

Are you possibly looking for references? OK, probably not.

In any case you're probably better off writing your own set of classes or functions, e.g.:

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

But if you're sure what you want is the best solution to the (unspecified) problem and $E = 'A->B'; $oj->E... is the syntax to go with, it should be possible with shudder magic methods. A set of recursive shudder __get()s should do the trick.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.