Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Anonymous functions in a class

Tags:

php

is there a better way to call an anonymous function inside a class? Here is a simple example that clearifies what I mean.

class foo
{
     private $call_back_1 = null;
     private $call_back_2 = null;

     function __construct($func1, $func2)
     {
          $this->call_back_1 = func1;
          $this->call_back_2 = func2;
     }


     function provokeCallBacks()
     {
          //this does not work, and gives an error  
          $this->call_back_1();


          //I would like to avoid this
          $method = $this->call_back_2;
          $method(); 
     }
}

$call1 = function(){ echo "inside call 1"};
$call2 = function(){ echo "inside call 2"};

$test = new foo(call1, call2);

$test->provokeCallBacks();

* Update 1: Please ignore any syntax error as I have written this on the fly for demo puposes. *

Inside foo:provokeCallBacks, I am trying to call the anonymous functions how ever the first way does not works and gives an error. The second one works but it's a bit stupid that I have to use a temp variable called "$method" to make the call.

I want to know if there exists a better way to call the anonymous function.

like image 513
thedethfox Avatar asked Mar 17 '26 09:03

thedethfox


2 Answers

call_user_func($this->call_back_1);
like image 142
Glavić Avatar answered Mar 18 '26 22:03

Glavić


No, it's not possible to call an anonymous function via $this.

Another options is;

call_user_func($this->call_back_1);
like image 43
Björn Avatar answered Mar 18 '26 22:03

Björn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!