错误:PHP Fatal error: Using $this when not in object context

  代码如下:

 1 <?php
 2 class someClass
 3 {
 4     private $success = "success\n";
 5 
 6     public function getReflection()
 7     {
 8         return new ReflectionFunction(function(){
 9             print $this->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

posted on 2016-09-22 15:45  睡着的糖葫芦  阅读(1175)  评论(0编辑  收藏  举报