简体   繁体   English

从字符串访问对象属性

[英]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; 我也知道下面的方法会起作用,但是它不能访问FGH属性。

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

So how is it possible to return the value of $obj->Test->FGH, from a string? 那么如何从字符串返回$ obj-> Test-> FGH的值呢?

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. 如果您要查找的属性是一个对象,则必须修改它,具体取决于$props数组是否为空。

The $props argument needs to be ordered in the same way the object properties are nested. $props参数需要按照嵌套对象属性的相同方式进行排序。

You could also modify it to have a string as second argument, for example Test/FGH 您还可以修改它以将字符串作为第二个参数,例如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'));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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