What is the difference between induction and type made by callable and Closure?
The difference is that in the type induction declaration, when we use Closure
, we are informing that that function or method must pass as parameter only anonymous functions.
In the case of the keyword callable
, when we use it as the type induction of the function or method parameter, we are stating that it will accept as a callback parameter, regardless of whether it is an anonymous function or not.
In this case, we must accept the following parameters that will be accepted:
string
representing static functions or methods. Ex: "print_r"
, "max"
, "Classe::nomeDoMetodo"
array
with two elements, representing classe
and método
. In this case, the first parameter can be an instance of objeto
(in the case of normal call) or the class string (in the case of static call). Ex: array('Classe', 'nomeDoMetodo')
or array(new Classe, 'nomeDoMetodo')
.
classe
implementing the magic method __invoke
(as is the case of the class Closure
for those who don’t know, a Closure
may have the method __invoke
accessed).
What is the advantage and use callable?
The main advantage can be seen with two examples:
Example without callable
:
function minha_funcao($callback)
{
if (is_callable($callback)) return $callback();
}
Example:
function minha_funcao($callback)
{
return $callback();
}
Observing: It is possible both in induction of type of Closure
and callable
it is possible to define a value NULL
by default.
So we can do this:
function minha_funcao($a, callable $func = NULL) {
if (! is_null($func)) return $a * 8;
return $func($a * 8);
}