查看callable
manual以查看将函数作为回调传递的所有不同方式.我在这里复制了该手册,并根据您的场景添加了每种方法的一些示例.
可呼叫
- PHP function以字符串的形式传递其名称.除了array()、echo、empty()、eval()、exit()、isset()、list()、print或unset()等语言构造之外,可以使用任何内置或用户定义的函数.
// Not applicable in your scenario
$this->processSomething('some_global_php_function');
- method of an instantiated object作为数组传递,该数组包含索引0处的对象和索引1处的方法名.
// 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']);
- Static class methods也可以通过传递类名而不是索引0处的对象来传递,而无需实例化该类的对象.
// 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+
- 除了常见的用户定义函数外,anonymous functions还可以传递给回调参数.
// Not applicable in your scenario unless you modify the structure
$this->processSomething(function() {
// process something directly here...
});