Anonymous function call clousuring $ this

I play with anonymous PHP 5.3 functions and try to emulate prototype based objects like javascript:

$obj = PrototypeObject::create(); $obj->word = "World"; $obj->prototype(array( 'say' => function ($ins) { echo "Hello {$ins->word}\n"; } )); $obj->say(); 

This sets "Hello World", the first parameter is an instance of the class (like python), but I want to use this variable when I call the i function:

 $params = array_merge(array($this),$params); call_user_func_array($this->_members[$order], $params); 

And try, with the results:

 call_user_func_array($this->_members[$order] use ($this), $params); 

Too complicated in the __set method:

 $this->_members[$var] use ($this) = $val; 

and

 $this->_members[$var] = $val use ($this); 

Any ideas?

+4
source share
1 answer

The parent area is inherited by use when creating an anonymous function. So what you are trying to do is impossible.

 $d = 'bar'; $a = function($b, $c) use ($d) { echo $d; // same $d as in the parent scope } 

Maybe something more like what you want:

 $obj->prototype(array( 'say' => function () use ($obj) { echo "Hello {$obj->word}\n"; } )); 

But the anonymous function will not be part of the class, and therefore, even if you must pass " $this " as a parameter via $obj , it will not be able to access the private data of the object.

+5
source

All Articles