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?
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.
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.
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.
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.
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...
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.
Use method_exists()
method_exists($obj, $method_name);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With