Cannot rebind scope of closure created from method, this will be an error in PHP 9¶
Description¶
When a closure is created from an object method ($obj->method(...)), its scope and binding are tied to the originating object. Attempting to rebind that closure to a different scope or object using Closure::bind() or Closure::bindTo() is not allowed.
In PHP 7.0, this was silently accepted. Since PHP 8.0, it raises a warning. In PHP 9.0, it will be a fatal error.
The restriction exists because a method-bound closure captures the object’s internal context. Rebinding it would violate encapsulation by granting access to private and protected members of an unrelated class.
Example¶
<?php
class X {
public function method() {}
}
class Y {}
$x = new X;
$fn = $x->method(...);
$fn->bindTo($x, Y::class);
?>
Literal Examples¶
Cannot rebind scope of closure created from method, this will be an error in PHP 9
Solutions¶
Create the closure from within the class itself using
[self, 'method']orClosure::fromCallable()to allow rebinding.Avoid rebinding method-bound closures; use
call_user_func()or$closure(...)with the original binding.If you need a rebound closure, create a standalone closure that wraps the method call.
See Also¶
In previous PHP versions, this error message used to be Cannot rebind scope of closure created from method.
Changed Behavior¶
This error may appear following an evolution in behavior, in previous versions. See ` <https://php-changed-behaviors.readthedocs.io/en/latest/behavior/.html>`_.