I've been looking through the laravel source code and I stumbled across this in the callStatic magic method:
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);
}
Why is the switch statement used first and then call_user_func_array()?
As Clive has mentioned in the comments; it's because of the performance concerns.
call_user_func_array()
is widely known for its performance issues. It's even slower than its sister functioncall_user_func()
by 10-20% as some benchmarks revealed.Here's the result of a benchmark ran to compare the performance of straight calls vs. dynamic calls vs. calls through
call_user_func*
functions:Paul M. Jones, another well-known PHP developer, also ran a benchmark on the exact same subject and concluded that:
Argument Unpacking
One last thing; As of PHP 5.6 and with the advent of argument unpacking operator (AKA spread, splat or scatter operator), you can safely rewrite that code to:
Quoting from the Argument Unpacking PHP RFC:
Also, see:
Argument unpacking advantages over
call_user_func_array