Silver Dragon
Silver Dragon

Reputation: 5560

Determining, if a variable is a valid closure in PHP

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

Upvotes: 34

Views: 22538

Answers (5)

mario
mario

Reputation: 145492

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

function is_closure($t) {
    return $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.)

Upvotes: 76

jjoselon
jjoselon

Reputation: 2811

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());

Upvotes: 0

Vad.Gut
Vad.Gut

Reputation: 531

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();
}

Upvotes: 4

Shire
Shire

Reputation: 398

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

Upvotes: 1

Phil
Phil

Reputation: 164897

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.

Upvotes: 17

Related Questions