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();

?>

Solutions

  • Remove $this from the use clause, since it is automatically available in the closure.

  • Use a static closure if $this is not needed.

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>`_.