Keyword callable in PHP

1

The keyword callable has been implemented since PHP 5.4.

It provides a way to type an argument of a function, forcing the argument type to be callback .

Example:

function minha_funcao($a, callable $func)
{
    return $func($a * 8); 
}

minha_funcao(9, function(){ return 5 * 10; });

I used, in cases like this, to use the Closure class to do the type induction of that second parameter.

Example:

function minha_funcao($a, \Closure $func)
{
}

So I have some questions

  • What is the difference between the induction of callable to Closure ?
  • What are the advantages of using callable ?
asked by anonymous 15.08.2015 / 14:30

1 answer

0

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);
}
    
15.08.2015 / 14:30