1

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()?

theintz
  • 1,946
  • 1
  • 13
  • 21
  • 1
    If u don't want to use `call_user_func` u'll need to assign the class member to a local member and invoke that member with `$member();` – DarkBee Nov 06 '14 at 16:04

1 Answers1

2

You might want to use __invoke on Closure:

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

// ⇒ Hello% 

Hope it helps.

Aleksei Matiushkin
  • 119,336
  • 10
  • 100
  • 160
  • I was writing a solution with variables and `call_user_func`, but this... Cheers. – Mike Nov 06 '14 at 16:09
  • I am writing an additional question on SO, just for you my dear friend. – Mike Nov 06 '14 at 16:11
  • This really is a new question, so, if you get a moment: http://stackoverflow.com/questions/26784428/invoke-on-callable-array-or-string – Mike Nov 06 '14 at 16:28
  • This only works when the callable is a Closure, not for callbacks like `array($instance, 'methodName')`. – theintz Nov 07 '14 at 09:28
  • Yes. Please refer to [this answer](http://stackoverflow.com/questions/26784428/invoke-on-callable-array-or-string/26784934#26784934) for what I could do for those callbacks. Actually `array($instance, 'methodName')` is by no means a callback. It is an array, containing instance and string. – Aleksei Matiushkin Nov 07 '14 at 09:43