dp610807 2017-02-16 06:16
浏览 309
已采纳

PHP - 从动态变量访问对象属性

I'm looking for accessing a property of a object property of an object like this :

$property = "user->name";
echo $object->$property; // ??, I want $object->user->name

I tried a lot of things, but none seems work.

Thanks

  • 写回答

3条回答 默认 最新

  • douchunxian9740 2017-02-16 06:37
    关注

    I don't think you can make multiple dereferences this way. You'll be looking for a variable in $object called user->name. Instead, you can split by -> and then make multiple calls, something like:

    $test = 'user->name';
    $var = $object;
    foreach(explode('->', $test) as $item) {
      $val = $val->$item;
    }
    echo $val;   # This is the result of $object->user->name
    

    Sample Code

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?