有没有一种方法可以确定一个已定义方法从该方法外部需要多少个参数?(PHP)

dqh*_*cks 2 php parameters methods

我正在创建一个MVC框架,该框架通过动作的方法参数将“动作”参数之后的所有url参数传递给请求的动作。

因此,如果网址是:

host/controller_name/action_name/param1/param2
Run Code Online (Sandbox Code Playgroud)

发生以下情况(当然是简化的):

$requested_controller = new controller_name();
call_user_func_array(array($requested_controller, action_name), array(param1, param2);
Run Code Online (Sandbox Code Playgroud)

问题出在错误报告中。如果请求的网址参数数量错误(动作需要两个参数,但网址仅包含一个参数,则会收到警告消息,然后造成严重破坏)。

由于这是程序错误而不是异常,因此我无法以任何方式尝试/捕获它,可以吗?有没有办法在尝试运行该操作方法之前检查它的预期参数数量?还是我应该以一种完全不同的方式来攻击它?

编辑(解决方案)

                $action_method_relfection = new ReflectionMethod($requested_controller, $requested_action);
                if (count($path_variables) < $action_method_relfection->getNumberOfRequiredParameters() || count($path_variables) > $action_method_relfection->getNumberOfParameters()) {
                    // if not, redirect to 404 error
                    self::redirect_to_404();
                }
Run Code Online (Sandbox Code Playgroud)

Pas*_*TIN 5

我想,使用Reflection API,您可以使用以下几种组合来找出每种方法接受的参数数量:


另一种解决方案是让您的方法只接受一个参数,并且始终接受一个参数:一个数组,该数组可以包含任意数量的项目。

这样,您总是传递一个参数,所有方法总是期望有一个参数;而且没有警告/错误了。