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?
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);
You can use method_exists()
. But this is a really bad idea
If $_POST['operation']
is set to some magic function names (like __set()), your code will still explode. Better use an array of allowed function names.