theintz
theintz

Reputation: 1987

Callback stored in class member, how to invoke?

Consider the following class:

class Callbackhandler() {
    private $cb;

    public function __construct(callable $cb) {
        $this->cb = $cb;
    }

    public function callme() {
        return $this->cb();
    }
}

Calling it as usual like so:

$callback = function() { return "Hello"; };
$handler = new Callbackhandler($callback);
echo $handler->callme();

produces a Call to undefined method error, because the field cb is not a method. How to properly invoke the callback from inside the class without using call_user_func()?

Upvotes: 1

Views: 40

Answers (1)

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121000

You might want to use __invoke on Closure:

public function callme() {
  return $this->cb->__invoke();
} 

// ⇒ Hello% 

Hope it helps.

Upvotes: 2

Related Questions