开发者

Call anonymous function clousuring $this

i'm playing with PHP 5.3 anonymous functions, and try to emulate the 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 puts "Hello World", the first param is the instance of the class (like python) but i want 开发者_如何学Pythonuse the this variable, when i call function i do:

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

And try it, with out results:

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

Too try, in __set method:

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

And

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

Any ideas?


The parent's scope is inherited by use when the anonymous function is created. So what you are trying to do is not possible.

$d = 'bar';

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

Perhaps something more like this is 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 as such, even if you were to pass "$this" as a parameter via $obj, it would not be able to access the object's private data.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜