Passing static methods as arguments in PHP

前端 未结 7 1481
温柔的废话
温柔的废话 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:15

    Since you've already mentioned that call_user_func() has been used and you're not interested in a solution with that or ones that are passing the static function as a string, here is an alternative: using anonymous functions as a wrapper to the static function.

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

    I wouldn't recommend doing this, as I think the call_user_func() method is more concise.

提交回复
热议问题