Cannot bind method %s::%s() to object of class %s, this will be an error in PHP 9

Description

A closure created from a non-static method ($obj->method(...) or Closure::fromCallable()) can only be bound to an instance of the class the method belongs to, or one of its subclasses. Binding it to an object of an unrelated class, as done above with an instance of Y while the method is defined on X, is not allowed.

Since PHP 8.5, this operation already emitted an E_WARNING and the bind silently failed, returning null. It is now deprecated and will become a fatal error in PHP 9.0.

Example

<?php

class X {
    public function method() {
        return __METHOD__;
    }
}

class Y {}

$x = new X;
$fn = $x->method(...);
$fn2 = Closure::bind($fn, new Y, Y::class);
var_dump($fn2);

?>

Literal Examples

  • Cannot bind method X::method() to object of class Y, this will be an error in PHP 9

Solutions

  • Bind the closure to an instance of the class that declares the method, or one of its subclasses.

  • If the method should work on unrelated classes too, extract the logic into a standalone function or a trait shared by both classes.

See Also

In previous PHP versions, this error message used to be Cannot bind method %s::%s() to object of class %s.

Changed Behavior

This error may appear following an evolution in behavior, in previous versions. See closure.