- function foo(callable $bar) PHP 5.4+
- function foo(callable $bar = null) PHP 5.4+
- function foo(): callable PHP 7.0+
- function foo(): ?callable PHP 7.1+
When type hinting, a closure must be an anonymous function, where a callable also can be a normal method/function.
- Closure is a class and callable is a type.
- The callable type accepts anything that can be called
function callableFunc(Callable $callback) {
$callback();
}
function closureFunc(Closure $closure) {
$closure();
}
function anyFunc(Callable $callable) {
$callable();
}
function testFunc() {
echo 'Hello, World!', "
";
}
$testClosure = function(){
echo 'Hello, World!', "
";
};
// gettype($testClosure); object
// var_dump($testClosure); object(Closure)#1 (0) { }
try{
closureFunc($testClosure); // Hello, World!
callableFunc("testFunc"); // Hello, World!
anyFunc($testClosure); // Hello, World!
callableFunc($testClosure); // Hello, World!
closureFunc("testFunc");// Argument 1 passed to closureFunc() must be an instance of Closure, string given
}
catch(TypeError $e){
echo $e->getMessage(), "
";
}
finally {
echo "Reachable statement";
}