Callback call saved as a member variable

Is it possible for php to directly call the callback stored in the member variable of the class? I'm currently using a workaround where I temporarily save my callback for 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() not a valid method, i.e. does not exist.

+4
source share
3 answers

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' 
+4
source

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)(); } } 
+4
source

In PHP 7 (I checked this only in 7.2), you can also assign a link to a local variable and call it:

 class A { private $cb; public function __construct($cb) { $this->cb = $cb; } public function doit($val) { $cb = $this->cb; return $cb($val); } } 
0
source

All Articles