在PHP中传递静态方法作为参数 [英] Passing static methods as arguments in PHP
问题描述
在PHP中,可以这样做:
In PHP is it possible to do something like this:
myFunction( MyClass::staticMethod );
,因此'myFunction'将引用静态方法并能够调用它。当我尝试它,我得到一个错误未定义的类常量(PHP 5.3)所以我想这不是直接可能,但有一个方法做类似的事情吗?我最近管理到目前为止是作为一个字符串传递函数,并使用call_user_func()。
so that 'myFunction' will have a reference to the static method and be able to call it. When I try it, I get an error of "Undefined class constant" (PHP 5.3) so I guess it isn't directly possible, but is there a way to do something similar? The closest I've managed so far is pass the "function" as a string and use call_user_func().
推荐答案
php way'要执行此操作,请使用 is_callable 使用的完全相同的语法, call_user_func 。
The 'php way' to do this, is to use the exact same syntax used by is_callable and call_user_func.
- 标准函式名称
- 静态类方法
- 实例方法
- 关闭
- A standard function name
- A static class method
- An instance method
- A closure
在静态方法的情况下,这意味着你应该传递它:
In the case of static methods, this means you should pass it as:
myFunction( [ 'MyClass', 'staticMethod'] );
或如果您尚未运行PHP 5.4:
or if you are not running PHP 5.4 yet:
myFunction( array( 'MyClass', 'staticMethod') );
这篇关于在PHP中传递静态方法作为参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!