dou4381 2016-04-20 09:14
浏览 69
已采纳

php类和方法从数组无法调用

I have an array $run that hold $run[0] - class name and $run[1] - class method to run and i want to be able to do this :

// this is working ok
$class = new $run[0]();
// this is error
$class->$run[1]();

What is the best and most elegant way of doing this ?

Thanks

  • 写回答

1条回答 默认 最新

  • dowbwrr3590709 2016-04-20 09:20
    关注

    Add {} around $run[1]: This uses an anonymous class which is available since PHP >= 7.0

    <?php
    $run = [];
    $run[0] = new Class {
    
        public function myMethod(){
            return 'Hello world';   
        }
    
    };
    $run[1] = 'myMethod';
    
    
    $class = new $run[0]();
    echo $class->{$run[1]}(); //Returns Hello world
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)