zoukankan      html  css  js  c++  java
  • PHP 使用reflection时的问题,以及解决方案

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

      代码如下:

     1 <?php
     2 class someClass
     3 {
     4     private $success = "success
    ";
     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

  • 相关阅读:
    bzoj1914
    bzoj3144
    bzoj2756
    poj3177
    一些比较水的题目
    bzoj2282
    屯题50AC纪念
    Base64解码中文部分中文乱码的原因
    随机生成36位字符串
    jQuery判断某个元素是否存在某个样式
  • 原文地址:https://www.cnblogs.com/loveyouyou616/p/5896664.html
Copyright © 2011-2022 走看看