php / php/php-src

Closure::bindTo Throwable instead of warning when passing object other class

Đang mở
#11,271 3 bình luận 0 reaction 0 người được giao Xem trên GitHub

Chưa có ai nhận issue này.

Feature Status: Needs Triage
Ngôn ngữ chính
C
Star
40.4k
Fork
8.2k
Merge trung bình
2 ngày 13 giờ
Pull request đã merge (30 ngày)
96

Mô tả

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

Hướng dẫn đóng góp

Mở hướng dẫn đóng góp

Bắt đầu từ đâu

  1. Đọc hết issue, rồi đọc hướng dẫn đóng góp của dự án.
  2. Bình luận trên issue rằng bạn sẽ nhận — tránh hai người làm cùng một việc.
  3. Fork repository và làm thay đổi trên một nhánh.
  4. Mở pull request có tham chiếu số hiệu của issue.

Hướng nghiên cứu

Bắt đầu với reproducer được cung cấp cho Closure::fromCallable() và bindTo(), sau đó kiểm tra entry point của Closure::bindTo và hành vi cảnh báo hiện tại. Công việc được xem là hoàn tất khi việc bind một object thuộc class không tương thích có thể được bắt dưới dạng Throwable, có coverage cho trường hợp được minh họa và không gây regression đối với các binding hợp lệ.

Do mô hình lập chỉ mục viết ra từ nội dung của issue.

Đánh giá

Công nghệ
c, php
Lĩnh vực
backend
Loại issue
Tính năng
Độ khó
4/5
Thời gian dự kiến
3-5 ngày
Mức độ hoạt động
Đình trệ
Độ rõ ràng
Khá rõ ràng
Mức phù hợp với người mới
35/100

Nhận issue mới trong hộp thư của bạn

Bản tóm tắt ngắn những issue GitHub phù hợp với người mới.