PHP method_exists() Function

What is PHP method_exists() Function?

If you want to check whether a method exists in an object or in a class, use method_exists() function.

Syntax:

method_exists(object_or_class, method_name)

Parameters:

The Function has 2 parameters which are required-

object_or_class (Required): It specifies the name of the object or the class.

method_name (Optional): It specifies the name of the method.

Return Values:

The function returns-

  • TRUE – if the method exists
  • FALSE – if the method doesn’t exist

Examples:

Example 1:

<?php
   class Human {
      public function eat() {}
   }
   $isExist = method_exists('Human', 'eat');
   echo $isExist ? "Method exists." : "Method not exists.";
?>

Output:

Method exists.

Example 2:

<?php
    class Human1 {
      public function eat() {}
   }
   $objHuman = new Human1();
   $isExist = method_exists($objHuman, 'eat');
   echo $isExist ? "Method exists." : "Method not exists.";
?>

Output:

Method exists.

Practical Usages of method_exists() Function:

Practical uses of the method_exists() function includes-

  • Before using a method, the function is used to check whether it is defined in a given class or object.
  • In MVC framework, developers used to use method_exists() function to check whether the requested controller action (method here) exists before calling it.
  • This function is used to avoid displaying “Call to Undefined Function”.
  • You can use this function in places when you can’t use strict interface or there might have probability of having method of an external library.

Notes on method_exists() Function:

  • This method can’t access those methods that only accessible through __call or__callStatic magic method.
  • This method can detect private, protected  or static methods.

PHP Version Support:

PHP 4, PHP 5, PHP 7, PHP 8

Summary: PHP method_exists() Function

method_exists() is a class/object type function in PHP. It is a frequently used function to check whether a method exists in a class or an object.

Reference:

https://www.php.net/manual/en/function.method-exists.php