Check if class has method in PHP

class, methods, oop, php

Solution

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...

Problem

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?

Original source