Pass a function by reference in PHP

前端 未结 9 1658
灰色年华
灰色年华 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 04:03

    You can say

    $fun = 'test'; 
    call($fun); 
    
    0 讨论(0)
  • 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

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

    For what it's worth, how about giving something like this a shot? (Yes, I know it's an anonymous function which was mentioned in the post, but I was disgruntled at the abundance of replies that did not mention closures/function-objects at all so this is mostly a note for people running across this post.)

    I don't use PHP, but using a closure appears to work in PHP 5.3 (but not PHP 5.2) as demonstrated here. I am not sure what the limitations, if any, there are. (For all I know the closure will eat your children. You have been warned.)

    function doIt ($fn) {
      echo "doIt\n";
      return $fn();
    }
    
    function doMe () {
      echo "doMe\n";
    }
    
    // I am using a closure here.
    // There may be a more clever way to "get the function-object" representing a given
    // named function, but I do not know what it is. Again, I *don't use PHP* :-)
    echo doIt(function () { doMe(); });
    

    Happy coding.

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