PHP is_callable
Banner image

PHP is_callable

method_exists() vs. is_callable()

One thing I often see when re-factoring PHP applications, is the improper use of the method_exists() function, and I think this needs a little bit of clarification.

Here is a typical example

if (method_exists($object, 'SomeMethod')) {
  $object->SomeMethod($this, TRUE);
This code snippet is intended to check for function and call it. Check an object named "$object", and see if it has a method named "SomeMethod", if so, we call it, and provide some arguments to it.

Yes but !!

This might work but what if the object’s method is not visible from the current scope (such as a private or protected method)? PHP’s method_exists() function does what it says on the tin. It checks if the provided class or object has a method with that given name, and returns TRUE if so, or otherwise FALSE. Visibility is not questioned. So, if you enquire after a private or protected method name that exists, (being out of current scope) to method_exists(), you’ll still get TRUE as the return value, and a nice "Fatal error: Call to private method…", immediately terminating the current script execution.

The right tool for the right job

is_callable() is part of the PHP built-in functions.
Website by Ibiscuits