How to call a function from a string stored in a variable?

后端 未结 16 2427
予麋鹿
予麋鹿 2020-11-22 10:16

I need to be able to call a function, but the function name is stored in a variable, is this possible? e.g:

function foo ()
{
  //code here
}

function bar ()
{
          


        
16条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-22 11:01

    Complementing the answer of @Chris K if you want to call an object's method, you can call it using a single variable with the help of a closure:

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

    I posted another example here

提交回复
热议问题