Search code examples
phpclosures

is there an is_closure() function, in PHP?


I have a var that I need to know if it's a closure or just a regular string, array, etc. Of course i could

is_array()
is_string()
is_bool()
is_null()
is_resource()
is_object()
no? must be a closure?

Solution

  • Note that is_callable() can return true on things that aren't closures -- like strings that contain the name of a function, arrays that reference a class and method, or instances of an object that implement __invoke():

    var_dump(is_callable('sort'));
    

    This yields:

    bool(true)
    

    You might do something like this, but I'm not positive it will cover all the cases:

    function is_closure($thing): bool
    {
        return
            !is_string($thing) &&
            !is_array($thing) &&
            !is_object($thing) &&
            is_callable($thing);
    }
    

    If you need to actually find closures versus callables, reflection might be best:

    function is_closure($thing): bool
    {
        try {
            return (new ReflectionClass($thing))->getName() === 'Closure';
        } catch (\Throwable $e) {
            return false;
        }
    }
    
    $thing = new stdClass();
    var_dump(is_closure($thing));
    
    $thing = function () { return 0; };
    var_dump(is_closure($thing));
    
    $thing = 'a string';
    var_dump(is_closure($thing));
    
    $thing = [1, 2, 3];
    var_dump(is_closure($thing));
    
    bool(false)
    bool(true)
    bool(false)
    bool(false)