Dynamic class method invocation in PHP

后端 未结 8 1993
感动是毒
感动是毒 2020-11-28 05:05

Is there a way to dynamically invoke a method in the same class for PHP? I don\'t have the syntax right, but I\'m looking to do something similar to this:

$t         


        
8条回答
  •  天涯浪人
    2020-11-28 05:14

    You can store a method in a single variable using a closure:

    class test{        
    
        function echo_this($text){
            echo $text;
        }
    
        function get_method($method){
            $object = $this;
            return function() use($object, $method){
                $args = func_get_args();
                return call_user_func_array(array($object, $method), $args);           
            };
        }
    }
    
    $test = new test();
    $echo = $test->get_method('echo_this');
    $echo('Hello');  //Output is "Hello"
    

    EDIT: I've edited the code and now it's compatible with PHP 5.3. Another example here

提交回复
热议问题