Passing static methods as arguments in PHP

前端 未结 7 1547
温柔的废话
温柔的废话 2021-02-02 07:34

In PHP is it possible to do something like this:

myFunction( MyClass::staticMethod );

so that \'myFunction\' will have a reference to the stati

7条回答
  •  情书的邮戳
    2021-02-02 08:17

    The 'php way' to do this, is to use the exact same syntax used by is_callable and call_user_func.

    This means that your method is 'neutral' to being

    • 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'] );
    

    or if you are not running PHP 5.4 yet:

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

提交回复
热议问题