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

时间:2013-10-22 20:42:05

标签: php object properties stdclass

我的情况很简单,但我仍然在寻找一个很好的简短解决方案。 这是我的情况:

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

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

$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";
    }
}

但不是因为参考" - >"。

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

这是之前测试的结果:

objTests的转储:

对象(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)

尝试使用字符串访问对象content2的proprerty prop3:

获取价值的标准方式:$ objTest-> Content2-> prop3

结果:3

测试字符串:" Content3"

结果:3

测试astring:" Content2-> prop3"

(!)注意:未定义的属性:stdClass :: $ Content2-> prop3

希望我把一切都用来帮助了解我的情况!

谢谢!

1 个答案:

答案 0 :(得分:1)

我不知道有一个内置的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;
}
相关问题