This question already has an answer here:
I have a class with methods which I want to use as callbacks. How to pass them as arguments?
Class MyClass {
public function myMethod() {
$this->processSomething(this->myCallback); // How it must be called ?
$this->processSomething(self::myStaticCallback); // How it must be called ?
}
private function processSomething(callable $callback) {
// process something...
$callback();
}
private function myCallback() {
// do something...
}
private static function myStaticCallback() {
// do something...
}
}
UPD: How to do the same but from static
method (when $this
is not available)
Check the
callable
manual to see all the different ways to pass a function as a callback. I copied that manual here and added some examples of each approach based on your scenario.Since 5.3 there is a more elegant way you can write it, I'm still trying to find out if it can be reduced more
You can also to use call_user_func() to specify a callback: