doucong6884 2016-06-26 16:41
浏览 55
已采纳

PHP多维对象属性从数组访问

I have an object which contain other objects. I have an array that describes what is the attributes i need to access. The Array can change in size.

My question is how can i access the sub-object attributes using the array?

Code example:

$student = new Student();
$arr = ['Grades', 'Score'];
foreach.... {}

expected result:

$student->$arr[0]->$arr[1];

I need to iterate over the $arr and access the $student sub-object

  • 写回答

1条回答 默认 最新

  • drk49438 2016-06-26 16:56
    关注

    Something like this:

    $student = new Student();
    $sub_object = $student;  // or use $student itself if you don't need it
    $arr = ['Grades', 'Score'];
    foreach ($arr as $v) {
        $sub_object = $sub_object->$v;
    }
    echo $sub_object;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi