php / php/php-src

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

Open
#11,271 3 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Feature Status: Needs Triage
Dominant language
C
Stars
40.4k
Forks
8.1k
Avg merge
2d 13h
Merged PRs (30d)
96

Description

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

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the provided Closure::fromCallable() and bindTo() reproducer, then inspect the Closure::bindTo entry point and current warning behavior. Done means binding an object of an incompatible class is catchable as Throwable, with coverage for the shown case and no regression for valid bindings.

Written by the indexing model from the issue text.

Assessment

Tech stack
c, php
Domain
backend
Issue type
Feature
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.