Callable keyword in PHP

Asked

Viewed 317 times

1

The keyword callable was implemented from PHP 5.4.

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

Example:

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

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

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

Example:

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

So I have a few questions

  • What is the difference between the induction of callable for Closure?
  • What are the advantages of using callable?

1 answer

0


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);
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.