Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if class has method in PHP

Currently my code looks like that:

switch ($_POST['operation']) {
    case 'create':
        $db_manager->create();
        break;
    case 'retrieve':
        $db_manager->retrieve();
        break;
...
}

What I want to do is, to check if method called $_POST['operation'] exists: if yes then call it, else echo "error" Is it possible? How can I do this?

like image 968
heron Avatar asked Apr 23 '12 20:04

heron


People also ask

How do you check if a method exists for a class?

Use the typeof operator to check if a method exists in a class, e.g. if (typeof myInstance. myMethod === 'function') {} . The typeof operator returns a string that indicates the type of the specific value and will return function if the method exists in the class.

How do you check if a function is defined in PHP?

The function_exists() is an inbuilt function in PHP. The function_exists() function is useful in case if we want to check whether a function() exists or not in the PHP script. It is used to check for both built-in functions as well as user-defined functions.

What are PHP methods?

Methods are used to perform actions. In Object Oriented Programming in PHP, methods are functions inside classes. Their declaration and behavior are almost similar to normal functions, except their special uses inside the class.

Is callable in PHP?

The is_callable() function checks whether the contents of a variable can be called as a function or not. This function returns true (1) if the variable is callable, otherwise it returns false/nothing.


3 Answers

You can use method_exists:

if (method_exists($db_manager, $_POST['operation'])){
  $db_manager->{$_POST['operation']}();
} else {
  echo 'error';
}

Though I strongly advise you don't go about programming this way...

like image 179
Brad Christie Avatar answered Oct 10 '22 23:10

Brad Christie


You can use is_callable() or method_exists().

The difference between them is that the latter wouldn't work for the case, if __call() handles the method call.

like image 28
zerkms Avatar answered Oct 11 '22 00:10

zerkms


Use method_exists()

method_exists($obj, $method_name);
like image 6
Kemal Fadillah Avatar answered Oct 10 '22 23:10

Kemal Fadillah