Closure::bindTo Throwable instead of warning when passing object other class
Nessuno ha ancora preso questa issue.
- Lingua principale
- C
- Stelle
- 40.4k
- Fork
- 8.1k
- Merge medio
- 2g 13h
- PR unite (30g)
- 96
Descrizione
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
Guida per i contributori
Apri la guida per i contributori
Come iniziare
- Leggi tutta la issue e poi la guida ai contributi del progetto.
- Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
- Fai un fork del repository e lavora su un branch.
- Apri una pull request che faccia riferimento al numero della issue.
Direzione di ricerca
Inizia con il riproduttore fornito per Closure::fromCallable() e bindTo(), quindi esamina il punto di ingresso di Closure::bindTo e il comportamento attuale degli avvisi. Il lavoro è completato quando il binding di un oggetto di una classe incompatibile può essere catturato come Throwable, con copertura per il caso mostrato e senza regressioni per i binding validi.
Scritto dal modello di indicizzazione a partire dal testo della issue.
Valutazione
- Stack tecnologico
- c, php
- Ambito
- backend
- Tipo di issue
- Funzionalità
- Difficoltà
- 4/5
- Tempo stimato
- 3-5 giorni
- Stato di attività
- Ferma
- Chiarezza
- Abbastanza chiara
- Idoneità per principianti
- 35/100