Home / How to check if a class method exists in PHP

How to check if a class method exists in PHP

Last week I looked at how to see if a function exists in PHP and this time will look at how to check if a class method exists in PHP.

Let’s say we have the following example PHP class:

class foo {

    function bar() {
       
    }
   
}

Use the method_exists() function to check to see if a method exists like so (the (int) part casts it as an integer so it will display 0 if false and 1 if true):

echo (int)method_exists('foo', 'bar');
echo (int)method_exists('foo', 'baz');

The first line will echo 1 (true) because the ‘bar’ method does exists in the ‘foo’ class. The second line will echo 0 (false) because the ‘baz’ method does not exist.

You can also pass an object itself to the method_exists() function:

$foo = new foo;
echo (int)method_exists($myfoo, 'bar');
echo (int)method_exists($myfoo, 'baz');

Again, the first line will echo 1 and the second line 0.

Note that if a method is declared as private or protected, the function will still return true if it exists, even though you will not be able to call it (although of course you can call a protected method if it’s a child class).

For example, a modified version of the above class:

class foo {

    function bar() {
       
    }
   
    protected function x() {
       
    }

    public function y() {
       
    }

    private function z() {
       
    }
  
}

And checking if the x, y, z methods exist:

echo (int)method_exists('foo', 'x');
echo (int)method_exists('foo', 'y');
echo (int)method_exists('foo', 'z');

Each of these will echo 1 because they do exist, although you may not be able to call them all. So use with caution!

In one of next week’s PHP posts I’ll look at the is_callable() function. Make sure to sign up to my RSS feed (see details below) so you don’t miss out.