Passing static methods as arguments in PHP

If you want to avoid strings, you can use this syntax:

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

It is a little verbose, but it has the advantage that it can be statically analysed. In other words, an IDE can easily point out an error in the name of the static function.


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.


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

Tags:

Php

Class

Static