Pass a function by reference in PHP

前端 未结 9 1699
灰色年华
灰色年华 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条回答
  •  -上瘾入骨i
    2020-12-29 04:08

    A similar pattern of this Javascript first class function:

    function add(first, second, callback){
        console.log(first+second);
        if (callback) callback();
    }
    
    function logDone(){
        console.log('done');
    }
    
    function logDoneAgain(){
        console.log('done Again');
    }
    add(2,3, logDone);
    add(3,5, logDoneAgain);
    

    Can be done in PHP (Tested with 5.5.9-1ubuntu on C9 IDE) in the following way:

    // first class function
    $add = function($first, $second, $callback) {
      echo "\n\n". $first+$second . "\n\n";
      if ($callback) $callback();
    };
    
    function logDone(){
      echo "\n\n done \n\n";
    }
    call_user_func_array($add, array(2, 3, logDone));
    call_user_func_array($add, array(3, 6, function(){
      echo "\n\n done executing an anonymous function!";
    }));
    

    Result: 5 done 9 done executing an anonymous function!

    Reference: https://github.com/zenithtekla/unitycloud/commit/873659c46c10c1fe5312f5cde55490490191e168

提交回复
热议问题