Cannot use $this as lexical variable
Description
A lexical variable is a variable imported into a closure via the use clause. Since PHP 8.1, $this is automatically available inside all closures defined in an object context, so it is no longer allowed to explicitly import it as a lexical variable. This is also true for arrow functions, which implicitly capture $this when defined inside a method.
Example
<?php
class X {
function foo() {
$fn = function () use ($this) {
return $this;
};
}
}
(new X)->foo();
?>
Alternatives
- Remove
$thisfrom theuseclause, since it is automatically available in the closure. - Use a
staticclosure if$thisis not needed.
Related error messages
- closures-in-constant-expressions-must-be-static
- using-$this-when-not-in-object-context
- cannot-use-auto-global-as-lexical-variable
Changed Behavior
This error may appear following an evolution in behavior, in previous versions. See