Closure::bindTo Throwable instead of warning when passing object other class
还没有人认领这个 Issue。
- 主要语言
- C
- 星标
- 40.4k
- 派生
- 8.2k
- 平均合并
- 2 天 13 小时
- 30 天内合并 PR
- 96
描述
Description:
Currently, when binding a new object to Closure, which is an object of a different class, a "warning" is logged in the log, but the method itself has no effect, which can be confusing.
It seems to me better to add Throwable in such a scenario, it will make it easier to handle the case.
The following code:
<?php
class SomeClass
{
public function testMethod() {
echo 123;
}
}
class OtherClass
{
public function testMethod() {
echo 234;
}
}
$a = new SomeClass();
$b = new OtherClass();
$closure = Closure::fromCallable([$a, 'testMethod']);
try {
$closure->bindTo($b);
} catch (Throwable $e) {
echo 'Oh, sorry u cannot do it!';
return;
}
$closure();
Resulted:
Warning: Cannot bind method SomeClass::testMethod() to object of class OtherClass in /in/VgKd4 on line 23
123
Expected:
Oh, sorry u cannot do it!
Workaround:
As it stands, to be able to handle such a scenario you need to use Reflection as follows:
$reflection = new ReflectionFunction($closure);
$oldThis = $reflection->getClosureThis();
if ($oldThis && $oldThis::class === $b::class) {
$closure->bindTo($b);
} else {
echo 'Oh, sorry u cannot do it!';
}
Of course, this code can be simplified, but a simple try/catch is a much better solution.
Especially since I assume that the parser will check again if the object is of the same class when executes bindTo()
PHP Version
PHP 8.2.6
Operating System
Linux
贡献指南
从这里开始
- 先读完整个 Issue,再读项目的贡献指南。
- 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
- Fork 仓库,在一个分支上完成修改。
- 提交 Pull Request,并在描述里引用这个 Issue 编号。
调研方向
先从提供的 Closure::fromCallable() 和 bindTo() 复现器开始,然后检查 Closure::bindTo 入口点和当前的警告行为。完成的标准是:绑定不兼容类的对象时可以将其作为 Throwable 捕获,并覆盖所示案例,且有效绑定没有回归。
由索引模型根据 Issue 内容生成。
评估
- 技术栈
- c, php
- 领域
- backend
- Issue 类型
- 功能
- 难度
- 4/5
- 预计耗时
- 3-5 天
- 活跃度
- 停滞
- 描述清晰度
- 基本清楚
- 新手友好度
- 35/100