检查类在 PHP 中是否有方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10287789/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 21:49:29  来源:igfitidea点击:

Check if class has method in PHP

phpoopclassmethods

提问by heron

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?

我想要做的是,检查调用的方法是否$_POST['operation']存在:如果存在则调用它,否则回显“错误”是否可能?我怎样才能做到这一点?

回答by Brad Christie

You can use method_exists:

您可以使用method_exists

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

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

尽管我强烈建议您不要以这种方式进行编程...

回答by zerkms

You can use is_callable()or method_exists().

您可以使用is_callable()method_exists()

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

它们之间的区别在于,如果__call()处理方法调用,后者不适用于这种情况。

回答by Kemal Fadillah

Use method_exists()

method_exists()

method_exists($obj, $method_name);

回答by iblue

You can use method_exists(). But this is a really bad idea

您可以使用method_exists(). 但这是一个非常糟糕的主意

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.

如果$_POST['operation']设置为一些神奇的函数名称(如__set()),您的代码仍然会爆炸。最好使用一组允许的函数名称。