5

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.

knittl
  • 246,190
  • 53
  • 318
  • 364
  • Similar question asked and answered [here](http://stackoverflow.com/questions/1656151/php-callable-object-as-object-member). Cliff notes version: "Mostly because of the loose typing. There's no way of actually infering what you might mean to do, so it defaults to erroring early." – Problematic Aug 10 '11 at 15:10
  • Perhaps `{$this->cb}()`? The `{}` should force PHP to see the cb reference as the `$cb` member var, and not as a cb method in the object. – Marc B Aug 10 '11 at 15:37
  • marc, no, »unexpected {, expecting _something else_ …« – knittl Aug 10 '11 at 15:39
  • Do you have a sample use case? – Foo Bah Aug 10 '11 at 15:59
  • @FooBah: allowing users of the class to provide a log function (see the question [PHP Callable Object as Object Member](http://stackoverflow.com/questions/1656151/php-callable-object-as-object-member)) – knittl Aug 10 '11 at 16:09

2 Answers2

10

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)();
  }
}
red_led
  • 343
  • 4
  • 7
6

You need to use 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'
Matthew
  • 15,464
  • 2
  • 37
  • 31
  • A pity I cannot call it directly, but I guess there's no way around using either `call_user_func` or storing the callback in a local var. Seems like the PHP parser is quite limited in some regards. `call_user_func` is as good as it gets, thanks! – knittl Aug 10 '11 at 16:47