调用匿名函数clousuring $ this

时间:2011-06-14 05:21:23

标签: php php-5.3

我正在使用PHP 5.3匿名函数,并尝试模拟基于原型的对象,如javascript:

$obj = PrototypeObject::create();

$obj->word = "World";

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

$obj->say();

这就是“Hello World”,第一个param是类的实例(比如python)但是我想使用这个变量,当我调用函数时我会这样做:

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

尝试一下,没有结果:

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

试试,在__set方法中:

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

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

有什么想法吗?

1 个答案:

答案 0 :(得分:5)

创建匿名函数时,父use继承父作用域。所以你要做的就是不可能。

$d = 'bar';

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

或许更像这样的东西就是你想要的:

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

但是匿名函数不会成为类的一部分,因此,即使您通过$this将“$obj”作为参数传递,它也无法访问对象的私人数据。

相关问题