将回调存储为成员变量

kni*_*ttl 5 php callback

有可能用php直接调用存储在类的成员变量中的回调吗?目前我正在使用一种解决方法,我暂时将我的回调存储到本地var.

class CB {
  private $cb;
  public function __construct($cb) {
    $this->cb = $cb;
  }
  public function call() {
    $this->cb(); // does not work
    $cb = $this->cb;
    $cb(); // does work
  }
}
Run Code Online (Sandbox Code Playgroud)

php抱怨这$this->cb()不是一个有效的方法,即不存在.

小智 9

在php7中你可以像这样调用它:

class CB {
  /** @var callable */
  private $cb;
  public function __construct(callable $cb) {
    $this->cb = $cb;
  }
  public function call() {
    ($this->cb)();
  }
}
Run Code Online (Sandbox Code Playgroud)


Mat*_*hew 6

您需要使用call_user_func

class CB {
    private $cb;
    public function __construct($cb) {
        $this->cb = $cb;
    }
    public function call() {
        call_user_func($this->cb, 'hi');
    }
}

$cb = new CB(function($param) { echo $param; });
$cb->call(); // echoes 'hi'
Run Code Online (Sandbox Code Playgroud)