Cannot rebind scope of closure created from function, this will be an error in PHP 9

Description

A closure created from a plain, top-level function (Closure::fromCallable('foo') or foo(...)) has no class scope: it was never attached to an object or a class in the first place. Passing a scope argument to Closure::bind() or Closure::bindTo() on such a closure has nothing to rebind.

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 {}

function foo() {
    return __FUNCTION__;
}

$fn = Closure::fromCallable('foo');
$fn2 = Closure::bind($fn, new X, X::class);
var_dump($fn2);

?>

Literal Examples

  • Cannot rebind scope of closure created from function, this will be an error in PHP 9

Solutions

  • Do not attempt to bind a scope to a closure created from a plain function; it has none.

  • If scoped behaviour is required, define the closure inside the class (as a method or a property initializer) instead of wrapping a free function.

See Also

Changed Behavior

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