Ale*_*lex 5 php call-user-func-array
我已经阅读了堆栈上有关使用call_user_func_array与仅调用该函数的其他答案,但我仍然无法收集何时应使用前者。call_user_func_array我知道当您不知道传递了多少个参数时,您可能想要使用,因此您可以这样做: $args = func_get_args();...但是如果要在函数中使用参数,您是否总是需要知道参数?
以下两项工作,我认为第一个的开销较小。
$format = new Foo;
$method = 'somemethod';
$arg = 'somevalue';
if (method_exists($format, $method)) {
return $format->$method($arg);
}
Run Code Online (Sandbox Code Playgroud)
与
return call_user_func_array(array($format, $method), array($arg));
Run Code Online (Sandbox Code Playgroud)
什么时候才能真正从使用中受益call_user_func_array?
假设您希望通过静态方法访问一个对象,如下所示:
Helper::load();
Run Code Online (Sandbox Code Playgroud)
好吧,这本身是行不通的,因为如果你看看具体的类,它没有静态方法:
class Helper {
public function load()
{
// Do some loading ...
}
public function aFunctionThatNeedsParameters( $param1, $param2 )
{
// Do something, and $param1 and $param2 are required ...
}
}
Run Code Online (Sandbox Code Playgroud)
因此,在第二个类中,我们可以这样做,因为上面的 Helper 类被加载到依赖注入容器中(请注意,这两个 Helper 类命名相同,但位于不同的命名空间中):
class Helper extends DIContainer {
public static $helper_instance = NULL;
public static function get_instance()
{
if( is_null( self::$helper_instance ) )
{
self::$helper_instance = parent::$container['helper'];
}
return self::$helper_instance;
}
public static function __callStatic( $method, $params )
{
$obj = self::get_instance();
return call_user_func_array( [ $obj, $method ], $params );
}
}
Run Code Online (Sandbox Code Playgroud)
问题是,可能还有另一个方法需要参数,即使我们的 load 方法没有任何参数。
所以在这种情况下我们可以使用Helper::load(), 但也Helper::aFunctionThatNeedsParameters( $param1, $param2 )
我认为这在 PHP 框架中被大量使用,这些框架知道静态类通常不合适,但他们希望能够像调用静态方法一样调用方法。我希望这是有道理的。