Using the is_callable function in PHP

Posted 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

is_callable can be used to check if a function exists like so:

function foo() {
}

echo (int)is_callable('foo');
echo (int)is_callable('bar');

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:

class wibble {

    function a() {
    }
    protected function b() {
    }
    public function c() {
    }
    private function d() {
    }

}

$wibble = new wibble;

echo (int)is_callable(array($wibble, 'a'));
echo (int)is_callable(array($wibble, 'b'));
echo (int)is_callable(array($wibble, 'c'));
echo (int)is_callable(array($wibble, 'd'));
echo (int)is_callable(array($wibble, 'e'));

'a' is a regular function so the output is 1.

'b' is a protected function and is not callable from the context so the output is 0. It would return true if is_callable was being called from a child class passing in $this.

'c' is callable because it is a public function and the output is 1.

'd' is not callable from the context because it is a private function so the output is 0. It would return true if is_callable was being called from the class itself passing in $this.

'e' is not callable because the function does not exist.

Note that if you use the __call() method in your class then is_callable() will always return true, unless you are testing for a declared function that is private or protected.



Related posts:


Comments