在PHP中将静态方法作为参数传递

All*_*ine 32 php static class

在PHP中可以做这样的事情:

myFunction( MyClass::staticMethod );
Run Code Online (Sandbox Code Playgroud)

这样'myFunction'将引用静态方法并能够调用它.当我尝试它时,我得到一个"Undefined class constant"(PHP 5.3)的错误,所以我想这不是直接可能的,但有没有办法做类似的事情?我到目前为止最接近的是将"函数"作为字符串传递并使用call_user_func().

Eve*_*ert 30

执行此操作的'php方式'是使用与is_callablecall_user_func完全相同的语法.

这意味着您的方法是"中立"的

  • 标准函数名称
  • 一个静态类方法
  • 实例方法
  • 关闭

对于静态方法,这意味着您应该将其传递为:

myFunction( [ 'MyClass', 'staticMethod'] );
Run Code Online (Sandbox Code Playgroud)

或者如果您还没有运行PHP 5.4:

myFunction( array( 'MyClass', 'staticMethod') );
Run Code Online (Sandbox Code Playgroud)


nic*_*ckb 9

既然你已经提到call_user_func()过已经使用过并且你对那些或者将静态函数作为字符串传递的解决方案不感兴趣,这里有一个替代方法:使用匿名函数作为静态函数的包装器.

function myFunction( $method ) {
    $method();
}

myFunction( function() { return MyClass::staticMethod(); } );
Run Code Online (Sandbox Code Playgroud)

我不建议这样做,因为我认为该call_user_func()方法更简洁.


lin*_*ogl 7

如果要避免使用字符串,可以使用以下语法:

myFunction( function(){ return MyClass::staticMethod(); } );
Run Code Online (Sandbox Code Playgroud)

它有点冗长,但它的优点是可以静态分析.换句话说,IDE可以很容易地指出静态函数名称中的错误.

  • @DanMan,它会在执行包装函数后立即执行. (3认同)

pro*_*mer 5

让我试着给出一个彻底的例子......

你会打这样的电话:

myFunction('Namespace\\MyClass', 'staticMethod');
Run Code Online (Sandbox Code Playgroud)

或者像这样(如果你想传递参数):

myFunction('Namespace\\MyClass', 'staticMethod', array($arg1, $arg2, $arg3));
Run Code Online (Sandbox Code Playgroud)

以及接收此电话的功能:

public static function myFunction($class, $method, $args = array())
{
    if (is_callable($class, $method)) {
        return call_user_func_array(array($class, $method), $args);
    }
    else {
        throw new Exception('Undefined method - ' . $class . '::' . $method);
    }
}
Run Code Online (Sandbox Code Playgroud)

类似的技术常用于php 中的Decorator模式.