PHP

PHP method_exists

It is a built-in method in PHP. The PHP method_exists function is used to check whether the class method exists or not in the program.

Syntax

method_exists(object or class, name_of_method);

Parameter

In the method_exists() function we have 2  parameters, first one is the object or class in which you find and the other one is the method name that will be found.

Return

The method_exists() function returns in Boolean expressions means true or false. It returns true if the method exists and returns false if it does not exists.

Example 1

<?php
class Books
{
    public function programming()
    {
        echo "hello world";
    }
}
$acc= new books();
if (method_exists(Books::class, 'programming')){
$acc->programming();
}
else{
  echo "it does not exist";
}
echo "<pre>";
$exi = method_exists(Books::class, 'des');
var_dump($exi); 
echo "</pre>";

In the above example, we first create a class named Books, and then we create a method of that class named programming after that we declare a variable equal to the object named new books and then we use the method_exists() function with if condition which will check the existence of the method and then the method will run and will print hello world. Then we use else condition if condition will not work so else will, after that we used pre tag and again used the method_exists function to check the existence of the non-exist method.

Let’s check the result.

Output

hello world

bool(false)

As you can see from the output the if method_exists() condition is working because the method exists in the class and the other method_exists() function gave a Boolean result (false) because the method named “des” does not exist.

Let’s try another example.

Example 2

<?php
class company
{
    public function office()
    {
        echo "it is a method";
    }
}
$a= new company();
if (method_exists(company::class, 'comp')){
$a->office();
}
else{
  echo "it is not an existing method";
}
echo "<pre>";
$exi= method_exists(company::class, 'office');
var_dump($exi); // bool(false)
echo "</pre>";

In the above example, we create a class company and a method named office and then check the function existence with the if condition this time we change the method name and then we create another method_exist() function in which we pass the actual existing method name lets check out the results.

Output

it is not an existing method
bool(true)

As you can see the else part of the if condition worked because the method name which we pass in the function does not exist and the other method-exist function worked correctly it gave a true value because the function office exists.

Conclusion

In this tutorial, we discussed the PHP method_exists() function. we saw the definition and solved some examples of the method.

Suggested Article:

Leave a Comment