Cannot unbind $this of method, this will be an error in PHP 9

Description

A closure created directly from a non-static method ($obj->method(...) or ReflectionMethod::getClosure()) is a $this-call in disguise: the method body may use $this freely, whether or not it is written explicitly. Since PHP 8.0 removed static calls to non-static methods, $this is guaranteed to exist whenever such a method runs, so bindTo(null) can no longer strip it.

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__;
    }
}

$x = new X;
$fn = $x->method(...);
$fn2 = $fn->bindTo(null);
var_dump($fn2);

?>

Literal Examples

  • Cannot unbind $this of method, this will be an error in PHP 9

Solutions

  • Keep the closure bound to the object; call it with the original binding instead of unbinding $this.

  • If a scope-free version of the logic is needed, extract it into a standalone function that does not rely on the method’s $this.

See Also

Changed Behavior

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