Determining, if a variable is a valid closure in PHP Determining, if a variable is a valid closure in PHP php php

Determining, if a variable is a valid closure in PHP


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.)


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.

UpdateThe 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.


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