php / php/php-src

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

Offen
#11,271 3 Kommentare 0 Reaktionen 0 zugewiesene Personen Auf GitHub ansehen

Dieses Issue hat noch niemand übernommen.

Feature Status: Needs Triage
Vorherrschende Sprache
C
Sterne
40.4k
Forks
8.1k
Ø Merge
2 T. 13 Std.
Gemergte PRs (30 T.)
96

Beschreibung

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

Beitragsleitfaden

Beitragsleitfaden öffnen

Erste Schritte

  1. Lies das ganze Issue und danach den Beitragsleitfaden des Projekts.
  2. Schreib ins Issue, dass du es übernimmst — das erspart doppelte Arbeit.
  3. Forke das Repository und arbeite in einem Branch.
  4. Öffne einen Pull Request, der die Issue-Nummer nennt.

Rechercherichtung

Beginne mit dem bereitgestellten Closure::fromCallable() und bindTo() Reproducer und untersuche anschließend den Closure::bindTo-Einstiegspunkt sowie das aktuelle Warnverhalten. Als abgeschlossen gilt die Arbeit, wenn das Binden eines Objekts einer inkompatiblen Klasse als Throwable abgefangen werden kann, mit Abdeckung für den gezeigten Fall und ohne Regression bei gültigen Bindings.

Vom Indexierungsmodell aus dem Issue-Text verfasst.

Bewertung

Tech-Stack
c, php
Bereich
backend
Issue-Typ
Feature
Schwierigkeit
4/5
Geschätzter Aufwand
3-5 Tage
Aktivitätsstatus
Veraltet
Klarheit
Größtenteils klar
Anfängerfreundlichkeit
35/100

Neue Issues direkt in Ihr Postfach

Eine kurze Übersicht über anfängerfreundliche GitHub-Issues.