Pass a function by reference in PHP

前端 未结 9 1713
灰色年华
灰色年华 2020-12-29 03:17

Is it possible to pass functions by reference?

Something like this:

function call($func){
    $func();
}

function test(){
    echo \"hello world!\";         


        
9条回答
  •  天命终不由人
    2020-12-29 03:56

    The problem with call_user_func() is that you're passing the return value of the function called, not the function itself.

    I've run into this problem before too and here's the solution I came up with.

    function funcRef($func){
      return create_function('', "return call_user_func_array('{$func}', func_get_args());");
    }
    
    function foo($a, $b, $c){
        return sprintf("A:%s B:%s C:%s", $a, $b, $c);
    }
    
    $b = funcRef("foo");
    
    echo $b("hello", "world", 123);
    
    //=> A:hello B:world C:123
    

    ideone.com demo

提交回复
热议问题