Pass a function by reference in PHP

前端 未结 9 1657
灰色年华
灰色年华 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:46

    You can create a reference by assigning the function to a local variable when you declare it:

    $test = function() {
        echo "hello world!";
    };
    
    function call($func){
        $func();
    }
    
    call($test);
    
    0 讨论(0)
  • 2020-12-29 03:52
    function func1(){
        echo 'echo1 ';
        return 'return1';
    }
    
    function func2($func){
        echo 'echo2 ' . $func();
    }
    
    func2('func1');
    

    Result:

    echo1 echo2 return1
    
    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-12-29 03:58

    In PHP 5.4.4 (haven't tested lower or other versions), you can do exactly as you suggested.

    Take this as an example:

    function test ($func) {
        $func('moo');
    }
    
    function aFunctionToPass ($str) {
        echo $str;
    }
    
    test('aFunctionToPass');
    

    The script will echo "moo" as if you called "aFunctionToPass" directly.

    0 讨论(0)
  • 2020-12-29 03:58

    Instead of call(test);, use call_user_func('test');.

    0 讨论(0)
  • 2020-12-29 04:02

    No, functions are not first class values in PHP, they cannot be passed by their name literal (which is what you're asking for). Even anonymous functions or functions created via create_function are passed by an object or string reference.

    You can pass a name of a function as string, the name of an object method as (object, string) array or an anonymous function as object. None of these pass pointers or references, they just pass on the name of the function. All of these methods are known as the callback pseudo-type: http://php.net/callback

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