class someClass {
private $success = "success\n";
function getReflection() {
return new ReflectionFunction(function() {
print $this->success;
});
}
}
$reflection = (new someClass)->getReflection();
$reflection->invoke();
当我运行它时,我得到一个
Fatal error: Using $this when not in object context in Command line code on line 5
这里发生了什么事?为什么$this
未在其中定义...?
由于我在方法内部的闭包中,$this
通常应进行定义。是的,我使用的是比PHP 5.4更高的版本。
我该如何解决?
ReflectionFunction在未绑定的闭包上运行。这就是为什么在ReflectionFunction::invoke()
调用之后,$this
在Closure中没有定义的变量,因此会出现致命错误。
但是有一种解决方法。
ReflectionFunction提供了三种必要的方法来通过$this
绑定进行调用:
ReflectionFunctionAbstract::getClosure()
ReflectionFunctionAbstract::getClosureThis()
ReflectionFunctionAbstract::getClosureScopeClass()
将ReflectionFunctionAbstract::getClosure()
仍然是未绑定的,但是我们可以通过其绑定Closure::bind()
。
所有Closure::bind()
需要的是Closure,要绑定的期望对象和类范围。
那么解决方案是:
call_user_func(\Closure::bind(
$reflection->getClosure(),
$reflection->getClosureThis(),
$reflection->getClosureScopeClass()->name));
我最初只想将其发布为问题,但是我在发布前就已经找到了解决方案,所以只需添加答案即可。上下文就是这个问题:https : //github.com/rdlowrey/Auryn/pull/72
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句