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

时间:2012-07-25 17:52:44

标签: php class static

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

myFunction( MyClass::staticMethod );

这样我的功能'将引用静态方法并能够调用它。当我尝试它时,我得到一个错误"未定义的类常量" (PHP 5.3)所以我想这不是直接可能的,但有没有办法做类似的事情?到目前为止,我所管理的最接近的是通过"功能"作为字符串并使用call_user_func()。

7 个答案:

答案 0 :(得分:27)

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

这意味着您的方法对于

是“中立的”
  • 标准功能名称
  • 静态类方法
  • 实例方法
  • 关闭

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

myFunction( [ 'MyClass', 'staticMethod'] );

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

myFunction( array( 'MyClass', 'staticMethod') );

答案 1 :(得分:9)

由于您已经提到已使用call_user_func()并且您对使用静态函数作为字符串传递的解决方案不感兴趣,因此这里有一个替代方法:使用匿名函数作为字符串静态函数的包装器。

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

myFunction( function() { return MyClass::staticMethod(); } );

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

答案 2 :(得分:7)

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

myFunction( function(){ return MyClass::staticMethod(); } );

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

答案 3 :(得分:5)

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

你会打这样的电话:

myFunction('Namespace\\MyClass', 'staticMethod');

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

myFunction('Namespace\\MyClass', 'staticMethod', array($arg1, $arg2, $arg3));

您接收此电话的功能:

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);
    }
}

类似的技术常用于php中的Decorator Pattern

答案 4 :(得分:3)

问题:

  

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

     

myFunction(MyClass :: staticMethod);

答案是肯定的。你可以让staticMethod()返回匿名函数。即。

private static function staticMethod()
{
    return function($anyParameters)
    {
        //do something here what staticMethod() was supposed to do
        // ...
        // ...
        //return something what staticMethod() was supposed to return;
    };
}
然后你可以写

myFunction(MyClass::staticMethod());

但请注意,调用staticMethod()需要()。这是因为它现在返回匿名函数,该函数包含了您最初希望staticMethod()执行的操作。

当staticMethod()仅作为参数传入另一个函数时,这非常有效。如果你想调用直接进行处理的staticMethod(),你必须编写

MyClass::staticMethod()($doPassInParameters);

请注意,这可能需要一个额外的冗余步骤来检索函数指针,相比之下它可以在不将其包装在匿名函数中的情况下工作。我只使用它作为参数传递,所以我不确定额外步骤的性能损失。也许可以忽略不计......

答案 5 :(得分:1)

这将显示 6为第一次通话 和第二次电话9 在输出中。

$staticmethod1 = function ($max)
{
    return $max*2;
};

$staticmethod2 = function ($max)
{
    return $max*$max;
};

function myfunction($x){
    echo $x(3);
}

myfunction($staticmethod1);
myfunction($staticmethod2);

答案 6 :(得分:0)

从PHP 7.4开始,这非常方便且对IDE友好:

myFunction(fn() => MyClass::staticMethod());
相关问题