PHP:如何使用类函数作为回调 [英] PHP: How to use a class function as a callback
本文介绍了PHP:如何使用类函数作为回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个带有要用作回调的方法的类.如何将它们作为参数传递?
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 :如何通过static
方法(当$this
不可用时)执行相同操作
UPD: How to do the same but from static
method (when $this
is not available)
推荐答案
检查 callable
手册,了解将函数作为回调传递的所有不同方式.我在此处复制了该手册,并根据您的情况添加了每种方法的一些示例.
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.
可通话
- PHP函数以其名称的形式作为字符串传递.可以使用任何内置或用户定义的函数,但语言构造除外,例如: array(), echo , empty(), eval(), exit(), isset(), list(), print 或 unset().
- A PHP function is passed by its name as a string. Any built-in or user-defined function can be used, except language constructs such as: array(), echo, empty(), eval(), exit(), isset(), list(), print or unset().
// Not applicable in your scenario
$this->processSomething('some_global_php_function');
- 实例化对象的方法作为数组传递,该数组包含索引为 0 的对象和方法名称为 1 的方法. /li>
- A method of an instantiated object is passed as an array containing an object at index 0 and the method name at index 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']);
- 静态类方法也可以通过传递类名称而不是索引为 0 的对象来传递而无需实例化该类的对象.
- Static class methods can also be passed without instantiating an object of that class by passing the class name instead of an object at index 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+
- 除了常见的用户定义函数外,匿名函数也可以传递给回调参数.
- Apart from common user-defined function, anonymous functions can also be passed to a callback parameter.
// Not applicable in your scenario unless you modify the structure
$this->processSomething(function() {
// process something directly here...
});
这篇关于PHP:如何使用类函数作为回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文