简体   繁体   中英

How to access a two-level objected using variables?

Example objects:

$this->obj1->lvl1
$this->obj1->lvl1->lvl2

I know I can access objects like this:

$var = 'obj1';
$this->{$var}

But I want to go further. The problem is that it needs to be dynamic so the name needs to come from a string. I'm using this for mapping. So a user can use dot notations to access anything in the object. So if the user uses this notation:

'obj1.lvl1'
'obj.lvl1.lvl2'

So all I have to do is:

$this->obj1->{$mapped_string}

So $mapped_string can go either one level or two or more levels deep.

It will map directly to the object. Anyone know how I can accomplish this?

Split the string into accessors, and then drill down in a loop. This works for any length of accessors:

$obj = $this;
$accessors = explode('.', $mapped_string);
foreach ($accessors as $acc) {
    $obj = $obj->{$acc};
}
var_dump($obj);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM