Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is there an is_closure() function, in PHP?

Tags:

closures

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?
like image 830
Doug Cassidy Avatar asked May 05 '26 18:05

Doug Cassidy


1 Answers

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)
like image 154
Alex Howansky Avatar answered May 07 '26 07:05

Alex Howansky



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!