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
A closure is an anonymous function that can access variables imported from the outside scope without using any global variables. Theoretically, a closure is a function with some arguments closed (e.g. fixed) by the environment when it is defined. Closures can work around variable scope restrictions in a clean way.
Use is_callable to determine whether a given variable is a function. For example: $func = function() { echo 'asdf'; }; if( is_callable( $func ) ) { // Will be true. }
A closure is a separate namespace, normally, you can not access variables defined outside of this namespace. There comes the use keyword: use allows you to access (use) the succeeding variables inside the closure. use is early binding. That means the variable values are COPIED upon DEFINING the closure.
The Closure class ¶Class used to represent anonymous functions. Anonymous functions yield objects of this type. This class has methods that allow further control of the anonymous function after it has been created. Besides the methods listed here, this class also has an __invoke method.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With