Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php is_function() to determine if a variable is a function

I was pretty excited to read about anonymous functions in php, which let you declare a variable that is function easier than you could do with create_function. Now I am wondering if I have a function that is passed a variable, how can I check it to determine if it is a function? There is no is_function() function yet, and when I do a var_dump of a variable that is a function::

$func = function(){     echo 'asdf'; }; var_dump($func); 

I get this:

object(Closure)#8 (0) { }  

Any thoughts on how to check if this is a function?

like image 605
Jage Avatar asked May 14 '10 16:05

Jage


People also ask

What is variable function PHP?

If name of a variable has parentheses (with or without parameters in it) in front of it, PHP parser tries to find a function whose name corresponds to value of the variable and executes it. Such a function is called variable function. This feature is useful in implementing callbacks, function tables etc.

When developing an application in PHP which function can you use to determine whether the variable is true of false?

The is_bool() function checks whether a variable is a boolean or not. This function returns true (1) if the variable is a boolean, otherwise it returns false/nothing.

How do you check if a variable contains a number in PHP?

The is_numeric() function checks whether a variable is a number or a numeric string. This function returns true (1) if the variable is a number or a numeric string, otherwise it returns false/nothing.

Are PHP functions callable?

Definition and Usage. The is_callable() function checks whether the contents of a variable can be called as a function or not. This function returns true (1) if the variable is callable, otherwise it returns false/nothing.


1 Answers

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. } 
like image 124
Jon Benedicto Avatar answered Sep 24 '22 07:09

Jon Benedicto