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().
Let my try to give a thorough example...
You would make a call like this:
or like this (if you have arguments you want to pass):
And your function to receive this call:
Similiar technique is commonly used in the Decorator Pattern in php.
to the question:
the answer is yes. you can have the staticMethod() return anonymous function instead. i.e.
you can then write
but note that () is needed to invoke staticMethod(). This is because it now returns the anonymous function that wraps the job of what you initially wanted your staticMethod() to do.
This works perfectly fine when staticMethod() is only being passed in as parameter into another function. If you wish to call staticMethod() that directly does the processing, you have to then write
Note that this may require one extra redundant step to retrieve the function pointer, as compared to when it can work without wrapping it in anonymous function. I only use it to pass as parameter so am not sure of the performance penalty of the extra step. Perhaps negligible ...
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.I wouldn't recommend doing this, as I think the
call_user_func()
method is more concise.this will show 6 for the the first call and 9 for the second call in output.
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
In the case of static methods, this means you should pass it as:
or if you are not running PHP 5.4 yet:
If you want to avoid strings, you can use this syntax:
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.