Check if class has method in PHP

泪湿孤枕 提交于 2019-12-05 10:55:57

问题


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?


回答1:


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




回答2:


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.




回答3:


Use method_exists()

method_exists($obj, $method_name);



回答4:


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.



来源:https://stackoverflow.com/questions/10287789/check-if-class-has-method-in-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!