What is the difference between the induction and type made by callable and Closure?
The difference is that in the type-induction declaration, when we use Closure
, we are saying that that function or method should pass as an only anonymous function parameter.
In the case of the keyword callable
, when we use it as a parameter type induction of the function or method, we are informing that it will accept as a parameter a callback, regardless of whether it is an anonymous function or not.
In this case, we must accept the following parameters that will be accepted:
-
string
that represent names of 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 a normal call) or the class string (in the case of a static call) .Ex: array('Classe', 'nomeDoMetodo')
or array(new Classe, 'nomeDoMetodo')
.
li>
-
What is the advantage and use callable?
The main advantage can be seen with two examples:
Example without classe
:
function minha_funcao($callback)
{
if (is_callable($callback)) return $callback();
}
Example:
function minha_funcao($callback)
{
return $callback();
}
Note : It is possible to both type __invoke
and Closure
to set a Closure
value 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);
}