php – How does the "is_callable" function work?

Question:

I don't quite understand how "is_callable" works in the following structure:

is_callable(array($controller, $metodo))

I know that it has something to do with the fact that a function can be called from a variable, but the documentation does not make it clear to me. Also, including an array makes it worse. Can you put more variables than two in the array?

Answer:

is_callable returns true if the argument(s) is/are callable/callable, or false otherwise.

If $controller is an instance of an object and $metodo is a public method of that class.

For example:

class UserController {
   public function index()
   {
   ...
   }
}

$controller = new UserController();
$metodo = 'index';

is_callable(array($controller, $metodo)) returns true because it is possible to make the call (there is an index method in the class): $controller->$metodo();

If it didn't exist, the $controller->$metodo() call would fail. This way is_callable protects you before doing the actual call.

is_callable takes a single argument, which will be interpreted as a global procedure/function. If an array is passed, the 1st element is interpreted as an instance of a class and the second a method of that class.

PS: Sorry the reply is late. Hope it helps others 😉

Scroll to Top