Using the is_callable function in PHP

The PHP function is_callable() tests to see if a function or class method can be called, and solves an issue with the method_exists() function which will return true for all methods regardless of whether or not they can actually be called.

I posted last week about how to check if a class method exists in PHP and noted at the end of the post that it will return true for private and protected methods as well. This is because it is simply checking to see if the method exists and not whether it is callable. Combined with (or used instead) the is_callable() function you can see if the class method/function is actually callable.

First I will look at using is_callable with a regular function and then with an object.

Check if a function is callable

The example code above declares a function called foo() and then uses is_callable by passing in the names of functions to check for. 'foo' exists and 'bar' doesn't. The (int) in front of the function call casts the function result as an integer and will therefore echo out either 1 or 0.

Because the function 'foo' exists, the first call will echo out 1 (true).

Because the function 'bar' does not exist, the second call will echo out 0 (false).

Check if a class method is callable

To check if a class method can be called in PHP also use the is_callable function but the object and method name must be passed in as an array. The following example illustrates this: