PHP instance of Closure vs is_callable or function_exists

The problem is that is_callable and function_exists check a string to see if it’s a function. But I wanted to check to see if it was an anonymous function and not a string. Turns out you can do this by checking for an instance of Closure:

if ( $fn instanceof Closure ) { $fn( ... ); }

One thought on “PHP instance of Closure vs is_callable or function_exists

  1. In the research I have been able to find, I have not yet come across a good enough explanation on why it matters.

    If I pass you a callable, it should not matter if it is a function, a static method of instance method. I want it to be called without restraint and your method disallows this freedom.

    Furthermore, with PHP 5.6 with varargs and rest, the limitations makes less sense.

    If I pass ‘my_function’ and you call:
    $callback($args…), they why does it still need to be a Closure object?

    What is the difference between:

    $callback = ‘my_function’;

    $callback = array(‘my_class’, ‘my_method’);

    $callback = array($myClass, ‘my_method’);


    $callback = function() use ($this) {};
    $callback = function() use ($obj) {};
    $callback = function() {};

    If each definition is function(…$args), then why does it matter what type of callable it is?

Leave a Reply