Some functions in PHP require a callback function.开发者_StackOverflow 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?
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)
.
function myFunc($param1, $param2, $callback) {
$data = get_data($param1, $param2)
$callback($data);
}
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;
});
精彩评论