OOP in PHP: Class-function from a variable?

前端 未结 3 1115
轮回少年
轮回少年 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 01:56

    Yes, it is possible, that is know as variable functions, have a look at this.

    Example from PHP's official site:

    <?php
    class Foo
    {
        function Variable()
        {
            $name = 'Bar';
            $this->$name(); // This calls the Bar() method
        }
    
        function Bar()
        {
            echo "This is Bar";
        }
    }
    
    $foo = new Foo();
    $funcname = "Variable";
    $foo->$funcname();  // This calls $foo->Variable()
    
    ?>
    

    In your case, make sure that the function do_the_thing exists. Also note that you are storing the return value of the function:

    $req = $class->$function_name();
    

    Try to see what the variable $req contains. For example this should give you info:

    print_r($req); // or simple echo as per return value of your function
    

    Note:

    Variable functions won't work with language constructs such as echo(), print(), unset(), isset(), empty(), include(), require() and the like. Utilize wrapper functions to make use of any of these constructs as variable functions.

    0 讨论(0)
  • 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}();
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题