Determining, if a variable is a valid closure in P

2019-02-16 07:49发布

问题:

Using the following function:

function is_closure($t) { return ( !is_string($t) && is_callable($t)); }

Can this return true for anything else, than an anonymous closure function? If so, what would be the correct way to determine, if a variable is a closure?

Many thanks

回答1:

The most deterministic way to check if a callback is an actual closure is:

function is_closure($t) {
    return is_object($t) && ($t instanceof Closure);
}

All anonymous functions are represented as objects of the type Closure in PHP. (Which, coming back to above comment, happen to implement the __invoke() method.)



回答2:

I think you can use instanceof Closure though the manual states this should not be relied upon. I guess it works for now.

Anonymous functions are currently implemented using the Closure class. This is an implementation detail and should not be relied upon.

Update The Closure manual page has updated its guidance on this. It appears that this behaviour can now be relied upon.

Anonymous functions, implemented in PHP 5.3, yield objects of this type. This fact used to be considered an implementation detail, but it can now be relied upon.



回答3:

php.net suggests using reflections to figure out if the variable contains a valid closure or not

I use this little helper

function isClosure($suspected_closure) {
    $reflection = new ReflectionFunction($suspected_closure);

    return (bool) $reflection->isClosure();
}


回答4:

This is supported with Reflection http://www.php.net/manual/en/reflectionfunctionabstract.isclosure.php



回答5:

If you get an error about that does not exist ReflectionFunction, use backslash before class:

// Closure
$closure = function () {}; 
$reflection = new \ReflectionFunction($closure);
// checkout if it is a closure
$test->isTrue($reflection->isClosure());