通过字符串访问更深层的对象属性

时间:2017-12-13 16:42:43

标签: php

我知道这看起来很奇怪,但只有在知道字符串的路径(" b-> c")时才需要访问更深层的对象属性,如下所示。

$a = new stdClass();
$a->b = new stdClass();

$a->b->c = "123";

$exp1 = "c";

$exp2 = "b->c";

print_r($a->b->$exp1); // works
print_r($a->$exp2);  // not so much

当只知道对象$ a并且具有类似" b-> c"的字符串时,可以访问$ a-> b-> c属性的任何方式。 ?

3 个答案:

答案 0 :(得分:1)

你可以用一小段代码来实现 - 这有效地将其分解为一次工作一级......

$a = new stdClass();
$a->b = new stdClass();

$a->b->c = "123";

$exp1 = "c";
$exp2 = "b->c";

print_r($a->b->$exp1); // works
print_r($a->$exp2);  // not so much
$val = $a;
foreach ( explode("->", $exp2) as $level )  {
    $val = $val->$level;
}
echo $val;

...输出

123PHP Notice:  Undefined property: stdClass::$b->c in /home/nigel/workspace/Architecture/test/test.php on line 18
PHP Stack trace:
PHP   1. {main}() /home/nigel/workspace/Architecture/test/test.php:0
123

答案 1 :(得分:1)

避免使用eval()的替代方法(在php 5.6中测试):

<?php

function getNestedProperties($object, $path)
{
    foreach (explode('->', $path) as $property) {
        if (!isset($object->$property)) {
            return null;
        }
        $object = $object->$property;
    }
    return $object;
}

运行此:

$a = new stdClass();
$a->b = new stdClass();
$a->b->c = "123";
$exp2 = "b->c";
var_dump(getNestedProperties($a, $exp2));

提供输出:

string(3) "123" 

答案 2 :(得分:0)

您可以使用eval()并将输出值捕获到变量。

$a = new stdClass();
$a->b = new stdClass();

$a->b->c = "123";

$exp1 = "c";

$exp2 = "b->c";

print_r($a->b->$exp1); // works
$out = '';
eval('$out = $a->'.$exp2.';');  // get value to $out with eval
print_r($out); // print it
相关问题