如何解决调用匿名函数来封闭$ this
|| 我正在使用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
\”作为参数,它也将无法访问该对象的私有数据。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。