【问题标题】:How to get an object property->property from a stdClass with a string representing it如何从带有表示它的字符串的stdClass中获取对象属性->属性
【发布时间】:2013-10-31 22:00:25
【问题描述】:

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

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

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

$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

测试字符串:“Content2->prop3”

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

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

谢谢!

【问题讨论】:

    标签: php object properties stdclass


    【解决方案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;
    }
    

    【讨论】:

    • 正是我想要的。我对此进行了一些修改,但所有基础知识都在那里!非常感谢!
    猜你喜欢
    • 1970-01-01
    • 2021-11-28
    • 1970-01-01
    • 2010-10-03
    • 2010-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多