问题描述
||
我正在使用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 \”,第一个参数是该类的实例(如python),但是当我调用函数时,我想使用this变量:
$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);
有任何想法吗?
解决方法
创建匿名函数时,父级的作用域由ѭ5继承。因此,您尝试执行的操作是不可能的。
$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\";
}
));
但是匿名函数不会成为该类的一部分,因此,即使您要通过$obj
传递\“$this
\”作为参数,它也将无法访问该对象的私有数据。