ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

php – 在不使用ReflectionFunction-> invoke()的对象上下文中使用$this

2019-06-09 20:15:38  阅读:248  来源: 互联网

标签:php this reflection fatal-error


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

这里发生了什么事?为什么$这里没有定义…?

因为我在方法中的Closure中,通常应该定义$this.是的,我的版本比PHP 5.4更新.

我该如何解决?

解决方法:

ReflectionFunction正在未绑定的闭包上运行.这就是为什么在ReflectionFunction :: invoke()调用之后,Closure中没有定义的$this变量,因此会出现致命错误.

但是有一种解决方法.

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

标签:php,this,reflection,fatal-error
来源: https://codeday.me/bug/20190609/1207042.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有