Call_user_func in the class context (with the specified value of $)

Is there a way to accomplish closure in PHP5.3 in the context of an object?

class Test { public $name='John'; function greet(){ eval('echo "Hello, ".$this->name;'); call_user_func(function(){ echo "Goodbye, ".$this->name; }); } } $c = new Test; $c->greet(); 

The eval () function will work fine, however, call_user_func will not have access to $ this. (Using $ this, if not in the context of the object). I pass "$ this" as an argument to close right now, but this is not quite what I need.

+4
source share
4 answers

Access to $this not possible from lambda or closure with PHP 5.3.6. You need to either assign $this to temp var, and use it with use (which means that you will only have an open API) or pass / use the required property. Everything is shown elsewhere on this site, so I will not repeat it.

Access to $this is available in Trunk, although for PHP.next: http://codepad.viper-7.com/PpBXa2

+6
source

For actual closure, this is the only way to do this:

 $obj = $this; call_user_func(function () use ($obj) { echo "Goodbye, " . $obj->name; }); 

It might be more elegant to pass an object as a parameter, as suggested in other answers (and probably how you already do this).

+4
source

What about:

 class Test { public $name='John'; function greet(){ eval('echo "Hello, ".$this->name;'); call_user_func(function($obj){ echo "Goodbye, ".$obj->name; }, $this); } } $c = new Test; $c->greet(); 
0
source
 call_user_func(function($name){ echo "Goodbye, ".$name; }, $this->Name); 
0
source

Source: https://habr.com/ru/post/1346705/


All Articles