php - Type hinting – Difference between `Closure` and `Callable`
223
I noticed that I can use either ofClosure
orCallable
as type hint if we expected some callback function to run. For example:
function callFunc1(Closure $closure) {
$closure();
}
function callFunc2(Callable $callback) {
$callback();
}
$function = function() {
echo 'Hello, World!';
};
callFunc1($function); // Hello, World!
callFunc2($function); // Hello, World!
Question
What's the difference here? In other words when to useClosure
and when to useCallable
or do they serve the same purpose?
Answer
Solution:
The difference is, that a
must be an anonymous function, where
also can be a normal function.
You can see/test this with the example below and you will see that you will get an error for the first one:
So if you only want to type hint anonymous function use:
Closure
and if you want also to allow normal functions usecallable
as type hint.Answer
Solution:
The main difference between them is that a
is a class and
a type.
The
callable
type accepts anything that can be called:Where a
closure
will only accept an anonymous function. Note that in PHP version 7.1 you can convert functions to a closure like so:.
Example:
So why use a
closure
overcallable
?Strictness because a
closure
is an object that has some additional methods:,
and
. They allow you to use a function declared outside of a class and execute it as if it was inside a class:
You would not like to call methods on a normal function as that will raise fatal errors. So in order to circumvent that you would have to write something like:
To do this check every time is pointless. So if you want to use those methods state that the argument is a
closure
. Otherwise just use a normalcallback
. This way; An error is raised on function call instead of your code causing it making it much easier to diagnose.On a side note: The
closure
class cannot be extended as its final.Answer
Solution:
It's worth mentioning that this won't work for PHP versions 5.3.21 to 5.3.29.
In any of those versions you will get an output like:
One can try that out using https://3v4l.org/kqeYD#v5321
Best regards,