这个开关声明不是废话吗?

Rob*_*bok 6 php switch-statement laravel laravel-5

我在Laravel 5核心中发现了这个奇怪的switch语句:

switch (count($args)) {
    case 0:
        return $instance->$method();
    case 1:
        return $instance->$method($args[0]);
    case 2:
        return $instance->$method($args[0], $args[1]);
    case 3:
        return $instance->$method($args[0], $args[1], $args[2]);
    case 4:
        return $instance->$method($args[0], $args[1], $args[2], $args[3]);
    default:
        return call_user_func_array([$instance, $method], $args);
Run Code Online (Sandbox Code Playgroud)

有没有理由为什么他们可能决定建立这样的东西而不是仅仅使用它?

return call_user_func_array([$instance, $method], $args);
Run Code Online (Sandbox Code Playgroud)

有什么好处?

hek*_*mgl 6

恕我直言,程序员避免call_user_func_array()了合理数量的典型调用$instance->method().当然,直接调用方法而不是使用它会更快call_user_func_array().代码是用爱写的:)

  • @RoboRobok我想这个代码的直接影响来自[本评论](http://php.net/manual/en/function.call-user-func-array.php#100794)关于PHP文档中的函数.Github显示该代码最初是在2010年1月提交的,因此作者很可能担心PHP 5.3中的性能. (3认同)