Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 890
Silver Dragon Avatar asked Aug 18 '11 01:08

Silver Dragon


People also ask

What are closures in PHP?

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.

How do I know if a function is worked in PHP?

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

What is a closure in PHP and why does it use the use identifier?

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.

What is PHP closure class?

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.


2 Answers

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

like image 95
mario Avatar answered Sep 22 '22 16:09

mario


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.

like image 31
Phil Avatar answered Sep 22 '22 16:09

Phil