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条)

报告相同问题?

悬赏问题

  • ¥15 给出完整的python代码并解释
  • ¥15 有人懂怎么做大模型的客服系统吗?卡住了卡住了
  • ¥20 firefly-rk3399上启动卡住了
  • ¥15 如何删除这个虚拟音频
  • ¥50 hyper默认的default switch
  • ¥15 网站打不开,提示502 Bad Gateway
  • ¥20 基于MATLAB的绝热压缩空气储能系统代码咨询
  • ¥15 R语言建立随机森林模型出现的问题
  • ¥15 关于#wpf#的问题:怎么更改LayoutGroup组件的标签页的字体颜色
  • ¥15 中级微观经济学,生产可能性边界问题