OOP in PHP: Class-function from a variable?

前端 未结 3 1116
轮回少年
轮回少年 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:16

    You can use ReflectionClass.

    Example:

    $functionName = 'myMethod';
    $myClass = new MyClass();
    $reflectionMyMethod = (new ReflectionClass($myClass))->getMethod($functionName);
    
    $relectionMyMethod->invoke($myClass); // same as $myClass->myMethod();
    

    Remember to catch ReflectionException If Method Not Exist.

提交回复
热议问题