调用匿名函数clousuring $ this

Exo*_*xos 4 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();
Run Code Online (Sandbox Code Playgroud)

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

$params = array_merge(array($this),$params);
call_user_func_array($this->_members[$order], $params);
Run Code Online (Sandbox Code Playgroud)

尝试一下,结果如下:

call_user_func_array($this->_members[$order] use ($this), $params);
Run Code Online (Sandbox Code Playgroud)

试试,在__set方法中:

$this->_members[$var] use ($this) = $val;
Run Code Online (Sandbox Code Playgroud)

$this->_members[$var] = $val use ($this);
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

Mat*_*hew 5

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

$d = 'bar';

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

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

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

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