Can I create a chain of PHP object references prog

2019-07-11 07:06发布

问题:

For example, I know how to take an arbitrary set of keys and use them to make object references like this...

$arr = array("A", "B", "C");
foreach($arr as $key):
    echo $obj->{$key} . "\n";
endforeach;
// prints $obj->A, $obj->B and $obj->C

But what if I have multiple levels of references within an object that I want to access? Is it possible to add more arrow operators on the fly?

$arr = array(array("A", "B"),
             array("C", "D", "E"),
             array("F"));
foreach($arr as $key_arr):
    // ???
endforeach;
// prints $obj->A->B, $obj->C->D->E, $obj->F

回答1:

You have to loop over the names and maintain a reference on the last object before to echo.

foreach($arr as $key_arr) {
    $ref = $obj ;
    foreach ($key_arr as $item) {
        $ref = $ref->{$item} ; // $obj->A, then $obj->A->B
    }
    echo $ref ;
}
  • $ref = $obj
  • Then $ref = $ref->A
  • Then $ref = $ref->B so $ref->A->B
  • And so on...
  • Then echo the last reference