简体   繁体   中英

Accessing an Object Property from a string

I would like to be able to access the value of a property from a single string...

$obj->Test->FGH = "Well Done!";

I have tried

var_dump($obj->{'Test->FGH'});

And

var_dump( eval( '$obj->Test->FGH' ) );

I know, the following will work, but it has to be defined from a string

var_dump ($obj->Test->FGH);

I also know the following will work, but it doesnt access the FGH property;

var_dump ($obj->{'Test'});

So how is it possible to return the value of $obj->Test->FGH, from a string?

You need to iterate through the object structure recursively until you find the property.

Here is a recursive function that does the job.

It only works if the searched value is not an object. You will have to modify it if the property you are looking for is an object, relying on wether the $props array is empty or not.

The $props argument needs to be ordered in the same way the object properties are nested.

You could also modify it to have a string as second argument, for example Test/FGH

function search_property($obj, $props) {

    $prop = array_shift($props);

    // If this is an object, go one level down
    if (is_object($obj->$prop)) {
        return search_prop($obj->$prop, $props);
    }

    if (!isset($obj->$prop)) {
        return false;
    }

    return $obj->$prop;

}

$val = search_property($obj, array('Test', 'FGH'));

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