Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/75.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在PHP中检查方法是否存在并具有参数_Php - Fatal编程技术网

如何在PHP中检查方法是否存在并具有参数

如何在PHP中检查方法是否存在并具有参数,php,Php,我想检查一个方法是否存在并且有参数。 这里有一些片段 // this only checks if the function exist or not if(method_exists($controller, 'function_name')) { //do some stuff } 但我想做的是 if(method_exists($controller, 'function_name(with_args)')) { } 函数重载或方法重载是一种功能,它允许创建具有相同名称的多个方

我想检查一个方法是否存在并且有参数。 这里有一些片段

// this only checks if the function exist or not
if(method_exists($controller, 'function_name')) 
{
  //do some stuff
}
但我想做的是

if(method_exists($controller, 'function_name(with_args)'))
{

}

函数重载或方法重载是一种功能,它允许创建具有相同名称的多个方法,这些方法在函数的输入和输出类型上彼此不同。不幸的是,这不是在php中实现的,使用方法重载不能有两个同名函数

为什么要使用函数\u exists使用函数重载?

您可以使用来获取方法的参数列表。然后,您可以检查该列表的长度,或者对参数执行所需的任何其他操作

<?php
    class Foo {
        function bar($a, $b, $c) {
            return $a + $b + $c;
        }
    }

    $method = new ReflectionMethod('Foo', 'bar');
    var_dump($method->getParameters());
?>


我不知道你会用这个做什么,但我建议不要随意使用反射。您可能会重新考虑您的工作方式。

PHP方法签名没有其他语言中定义的那么严格。方法的签名中不能有任何已定义的参数,并且仍然接受参数。谢谢@AlexTurpin。我正在使用MVC指南创建一个应用程序,我正在创建一个控制器,它基本上采用url地址并相应地实例化一个类,其中一些类具有函数,一些类具有参数。因此,我想在调用之前检查weather函数是否存在并有参数。@如果您担心这种严格的检查,那么在这种情况下,我可能会建议您使用错误的语言;)感谢我和其他以前回答过你问题的人的最好方式就是回答你的问题!