Menu

Error Identifier: closure.useThis

← Back to closure.*

Every error reported by PHPStan has an error identifier. Here’s a list of all error identifiers. In PHPStan Pro you can see the error identifier next to each error and filter errors by their identifiers.

Code example #

<?php declare(strict_types = 1);

class Foo
{
	public function doFoo(): void
	{
		$fn = static function () use ($this) {
			echo $this->bar();
		};
	}

	public function bar(): string
	{
		return 'bar';
	}
}

Why is it reported? #

The $this variable cannot be used as a lexical variable in a closure’s use clause. PHP does not allow use ($this) – it is a syntax error. Non-static closures already have access to $this automatically, so importing it is both unnecessary and invalid.

How to fix it #

Remove $this from the use clause and make the closure non-static so it has access to $this:

 <?php declare(strict_types = 1);
 
 class Foo
 {
 	public function doFoo(): void
 	{
-		$fn = static function () use ($this) {
-			echo $this->bar();
+		$fn = function () {
+			echo $this->bar();
 		};
 	}

 	public function bar(): string
 	{
 		return 'bar';
 	}
 }

Non-ignorable error #

This error cannot be ignored using @phpstan-ignore or the ignoreErrors configuration. Non-ignorable errors indicate code that would cause a crash or a fatal error at runtime, or a fundamental problem in the analysed code that must be addressed.

Rules that report this error #

  • PHPStan\Rules\Functions\ClosureUsesThisRule [1] phpstan/phpstan-strict-rules
  • PHPStan\Rules\Functions\InvalidLexicalVariablesInClosureUseRule [1]
Theme
A
© 2026 PHPStan s.r.o.