3

Some functions in PHP require a callback function. How can I do this in a function myself? First of all, how do I define a function that require a callback function?

And secondly, how do I provide a custom function as the callback function? How do I provide a regular function, an instance function and a static function?

Svish
  • 152,914
  • 173
  • 462
  • 620
  • read the manual - http://php.net/manual/en/language.pseudo-types.php .This is the first result for a google search on "php callback function" – thetaiko Oct 25 '10 at 15:45
  • possible duplicate of [How do I implement a callback in PHP?](http://stackoverflow.com/questions/48947/how-do-i-implement-a-callback-in-php) – Gordon Oct 25 '10 at 15:52
  • Keep in mind that PHP 5.3 introduced closures, and thus callback usage can be different between pre-5.3 and 5.3+. – erjiang Oct 25 '10 at 16:58

3 Answers3

1

You could use type hinting to force someone to use a specific type of variable.

function test(callable $test){
    echo __LINE__.PHP_EOL;
    $test();
    echo __LINE__.PHP_EOL;
}

test(function(){
    echo __LINE__.PHP_EOL;
});
cwouter
  • 719
  • 6
  • 5
1
function myFunc($param1, $param2, $callback) {
   $data = get_data($param1, $param2)
   $callback($data);
}
Alex Rashkov
  • 9,833
  • 3
  • 32
  • 58
1

Use the built in call_user_func(). It may be necessary to use call_user_func_array()

function work($a, $c) {
  $a = filter($a)
  if(!is_callable($c) || !call_user_func($c, $a)) {
    return 0; // throw error
  } else {
    return 1; // return success
  }
}

This is safer than just doing $c($a) a.k.a passed_callback(passed_argument) because checking to see if the function actually exists is done for you, though some have commented on performance degradation over $c($a).

Andrew Sledge
  • 10,163
  • 2
  • 29
  • 30
  • 1
    Might be better to use is_callable() first, to ensure $c is a callable function. – mellowsoon Oct 25 '10 at 16:21
  • I'd probably use something similar to your code just to be complete, but I'm not sure it makes a difference. Passing a non-callable function is going to cause one of two things: Your code is going to throw an error because you used is_callable, or PHP is going to throw an error because $c() isn't a valid callback. The end result is the same, but the latter is faster because it avoids calling is_callable and call_user_func. – mellowsoon Oct 25 '10 at 16:59