如何从 stdClass 中获取对象属性>属性,并用字符串表示它


How to get an object property->property from a stdClass with a string representing it

我的情况很简单,但我仍在为它寻找一个漂亮而简短的解决方案。这是我的情况:

我收到一个 soap 响应对象,它与对另一个调用不同。有时,这些属性本身就是对象,可能具有我们必须获取的属性。为此,为每种类型的调用设置一个数组,以选择所需的数据并丢弃其余数据。

例如,在调用中,我们收到如下对象:(我通过模拟接收到的对象使代码易于测试)

$objTest = new stdClass();
$objTest->Content1 = "";
$objTest->Content2 = new stdClass();
$objTest->Content2->prop1=1;
$objTest->Content2->prop2=2;
$objTest->Content2->prop3=3;
$objTest->Content3 = 3;
$objTest->Content4 = array('itm1'=>1, 'itm2'=>'two');

我想检查是否存在 $objTest->Content2->prop3,但我不知道我正在寻找这个,因为我正在寻找的是关联数组。

调用的数组如下所示:

$map = array('Content3','Content2->prop3');

从现在开始,我可以通过这样做来获取 Content3 属性的内容:

foreach ($map as $name => $value) {
    if (isset($object->$name)) {
        echo "$value: ". json_encode($object->$name)."'n";
    }
}

但不适用于另一个,因为引用"->"。

现在我的问题:有没有办法获取上面显示的未知对象的未知属性?

这是上一个测试的结果:

Dump of objTests:

object(stdClass)[1]

public 'Content1' => string '' (length=0)
public 'Content2' => object(stdClass)[2]
    public 'prop1' => int 1
    public 'prop2' => int 2
    public 'prop3' => int 3
public 'Content3' => int 3
public 'Content4' => array (size=2)
    'itm1' => int 1
    'itm2' => string 'two' (length=3)

尝试使用字符串访问对象的内容 2 的专有 prop3:

获取值的标准方法:$objTest->内容2->prop3

结果 : 3

测试字符串:"内容3"

结果:3

测试涩音:"内容2->prop3"

( !注意:未定义的属性:标准类::$Content 2->prop3

希望我尽一切努力帮助了解我的情况!

谢谢!

我不知道有

内置的PHP函数可以做到这一点,但是可以使用一个函数来分解属性字符串并遍历它们以查找字符串中最后一个属性的值。

function get_property($object, $prop_string, $delimiter = '->') {
    $prop_array = explode($delimiter, $prop_string);
    foreach ($prop_array as $property) {
        if (isset($object->{$property}))
            $object = $object->{$property};
        else
            return;
    }
    return $object;
}