错误:PHP Fatal error: Using $this when not in object context
代码如下:
<?php
class someClass
{
private $success = "success\n"; public function getReflection()
{
return new ReflectionFunction(function(){
print $this->success;
});
}
} $reflection = call_user_func([new someClass(),'getReflection']);
$reflection->invoke();
原因:ReflectionFunction is operating on unbound Closures. That's why after the ReflectionFunction::invoke() call, there's no defined $this variable inside the Closure and as such your fatal error appears. ReflectionFunction 操作了一个并没有绑定对象($this)的匿名函数
解决方案:利用 Closure::bind 改变作用域
$reflection = call_user_func([new someClass(),'getReflection']);
//var_dump($reflection->getClosureScopeClass()->name); //string(9) "someClass"
call_user_func(Closure::bind(
$reflection->getClosure(), //需要绑定的匿名函数。
$reflection->getClosureThis(), //需要绑定到匿名函数的对象,或者 NULL 创建未绑定的闭包。
$reflection->getClosureScopeClass()->name //想要绑定给闭包的类作用域
));
结果:success