php callback function 調用的幾種姿勢

搬磚時遇到的一點點關於回調函數(callback function)的總結。

  1. 一般函數
$this->callSomeFunction('some_global_php_function');
  1. 對象實例方法
// Only from inside the same class
$this->callSomeFunction([$this, 'myCallback']);

// From either inside or outside the same class
$myObject->callSomeFunction([new MyClass(), 'myCallback']);

備註:提供給其他對象的回調函數別忘記訪問控制(public)。

  1. 靜態類方法
// 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+
  1. 匿名函數
$this->callSomeFunction(function() {
	// do something in anonymous function
});
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章