dongpanshi2839 2012-11-28 10:22
浏览 43
已采纳

如何通过PHP中的变量引用选择对象的子对象?

I have an object in PHP (in my case, a CakePHP model), that has child objects, eg. the structure of $this->Model1->Model2.

I am aware that the above syntax is the correct way to reference the object, but if I have obtained the name of Model2 via another process, so it is a string variable. How can I reference it using this variable, similar to as follows:

$model_name = 'Model2';
$this->Model1[ $model_name ]->run_function();

Now clearly this array-style of selecting the object/class doesn't work, but is there a similar method I should be using? Or is there better coding practice that wouldn't result in this issue all together?

  • 写回答

2条回答 默认 最新

  • doushun1870 2012-11-28 10:25
    关注

    Are you looking for this?

    $property = 'myProperty';
    $object->{$property};
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 linux驱动,linux应用,多线程