Passing static methods as arguments in PHP

Viewed 16082

In PHP is it possible to do something like this:

myFunction( MyClass::staticMethod );

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().

8 Answers

This is because of the difference between passing constant and function. Passing parameter name without parentheses means constant(MyClass::staticMethod) and with parentheses it means a static function(MyClass::staticMethod()).

As of PHP 7.4, this is convenient and IDE-friendly:

myFunction(fn() => MyClass::staticMethod());
Related