php - 如何使用类方法作为回调

标签 php oop callback

我有一个类,其中包含我想用作回调的方法。
如何将它们作为参数传递?

Class MyClass {
    
    public function myMethod() {
        // How should these be called?
        $this->processSomething(this->myCallback);
        $this->processSomething(self::myStaticCallback);
    }

    private function processSomething(callable $callback) {
        // Process something...
        $callback();
    }

    private function myCallback() {
        // Do something...
    }

    private static function myStaticCallback() {
        // Do something...
    }   
    
}

最佳答案

查看callable manual查看将函数作为回调传递的所有不同方式。我在此处复制了该手册,并根据您的情况添加了每种方法的一些示例。

Callable


  • 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');

  • 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']);

  • 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 - 如何使用类方法作为回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28954168/

相关文章:

javascript - 如何从 javascript 回调返回字符串

php - 我可以使用私有(private)实例方法作为回调吗?

php - 使用未定义的常量主机 - 假定 'host' Paypal 类中的错误(codeigniter 库)

PHP 在单个数字前添加前导零,即时

php - Yii CUserIdentity 与用户模型

Java 内部类和扩展

javascript - 如何使用 promises 和 node.js 正确检查和记录 http 状态代码?

php - Stripe TLS 1.2 升级问题

php - WkhtmlToPdf 多种字体/样式

c++ - 如何继承方法 operator=、clone 和 dispose