OOP in PHP: Class-function from a variable?

前端 未结 3 1114
轮回少年
轮回少年 2021-02-12 01:54

Is it possible to call functions from class like this:

$class = new class;
$function_name = \"do_the_thing\";
$req = $class->$function_name();
3条回答
  •  鱼传尺愫
    2021-02-12 02:15

    My easiest example is:

    $class = new class;
    $function_name = "do_the_thing";
    $req = $class->${$function_name}();
    

    ${$function_name} is the trick

    Also works with static methods:

    $req = $class::{$function_name}();
    

提交回复
热议问题