搬磚時遇到的一點點關於回調函數(callback function)的總結。
- 一般函數
$this->callSomeFunction('some_global_php_function');
- 對象實例方法
// Only from inside the same class
$this->callSomeFunction([$this, 'myCallback']);
// From either inside or outside the same class
$myObject->callSomeFunction([new MyClass(), 'myCallback']);
備註:提供給其他對象的回調函數別忘記訪問控制(public)。
- 靜態類方法
// Only from inside the same class
$this->callSomeFunction([__CLASS__, 'myStaticCallback']);
// From either inside or outside the same class
$myObject->callSomeFunction(['\Namespace\MyClass', 'myStaticCallback']);
$myObject->callSomeFunction(['\Namespace\MyClass::myStaticCallback']); // PHP 5.2.3+
$myObject->callSomeFunction([MyClass::class, 'myStaticCallback']); // PHP 5.5.0+
- 匿名函數
$this->callSomeFunction(function() {
// do something in anonymous function
});