PHP 使用reflection时的问题,以及解决方案

本文介绍了一种常见的PHP错误——在非对象上下文中使用$this,并提供了详细的解决方案。通过使用Closure::bind方法,可以成功地将匿名函数绑定到指定对象的作用域内,避免出现致命错误。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  错误: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

转载于:https://www.cnblogs.com/loveyouyou616/p/5896664.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值