错误:PHP Fatal error: Using $this when not in object context
代码如下:
1 success;10 });11 }12 }13 14 $reflection = call_user_func([new someClass(),'getReflection']);15 $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 改变作用域
1 $reflection = call_user_func([new someClass(),'getReflection']);2 //var_dump($reflection->getClosureScopeClass()->name); //string(9) "someClass"3 call_user_func(Closure::bind(4 $reflection->getClosure(), //需要绑定的匿名函数。5 $reflection->getClosureThis(), //需要绑定到匿名函数的对象,或者 NULL 创建未绑定的闭包。6 $reflection->getClosureScopeClass()->name //想要绑定给闭包的类作用域7 ));
结果:success