Problem
I have a class that contains methods that I’d like to use as callbacks. How may they be used 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...
}
}
UPDATE: How to perform the same thing with a static method (in the case where $this isn’t available)
Asked by SmxCde
Solution #1
To learn about all the many ways to pass a function as a callback, consult the callable manual. I’ve copied that guidebook into this document and given some examples of each option based on your situation.
// Not applicable in your scenario
$this->processSomething('some_global_php_function');
// Only from inside the same class
$this->processSomething([$this, 'myCallback']);
$this->processSomething([$this, 'myStaticCallback']);
// From either inside or outside the same class
$myObject->processSomething([new MyClass(), 'myCallback']);
$myObject->processSomething([new MyClass(), 'myStaticCallback']);
// Only from inside the same class
$this->processSomething([__CLASS__, 'myStaticCallback']);
// From either inside or outside the same class
$myObject->processSomething(['\Namespace\MyClass', 'myStaticCallback']);
$myObject->processSomething(['\Namespace\MyClass::myStaticCallback']); // PHP 5.2.3+
$myObject->processSomething([MyClass::class, 'myStaticCallback']); // PHP 5.5.0+
// Not applicable in your scenario unless you modify the structure
$this->processSomething(function() {
// process something directly here...
});
Answered by MikO
Solution #2
There is a more elegant method to write it since 5.3, and I’m currently trying to figure out if it can be cut even further.
$this->processSomething(function() {
$this->myCallback();
});
Answered by Bankzilla
Solution #3
You may also define a callback with call user func():
public function myMethod() {
call_user_func(array($this, 'myCallback'));
}
private function myCallback() {
// do something...
}
Answered by Geovani Santos
Post is based on https://stackoverflow.com/questions/28954168/php-how-to-use-a-class-function-as-a-callback