Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call callback stored as member variable

Tags:

php

callback

Is it possible with php to directly call a callback stored in an member variable of a class? currently I'm using a workaround, where I'm temporarily storing my callback to a local 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
  }
}

php complains that $this->cb() is not a valid method, i.e. does not exist.

like image 292
knittl Avatar asked Aug 10 '11 15:08

knittl


1 Answers

In php7 you can call it like this:

class CB {
  /** @var callable */
  private $cb;
  public function __construct(callable $cb) {
    $this->cb = $cb;
  }
  public function call() {
    ($this->cb)();
  }
}
like image 82
red_led Avatar answered Oct 01 '22 13:10

red_led