Menu

← Back to closure.*

Error Identifier: closure.useThis

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
	{
		$self = $this;
		$fn = function () use ($self) {
			$self->doSomething();
		};
	}

	public function doSomething(): void
	{
	}
}

Why is it reported? #

The closure uses $this assigned to another variable in its use clause. Non-static closures in PHP already have access to $this automatically, so passing it through a variable is unnecessary and less clear.

This can also be reported when $this is directly placed in the use clause (use ($this)), which is a PHP syntax error.

How to fix it #

Use $this directly inside the closure body:

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

 	public function doSomething(): void
 	{
 	}
 }

How to ignore this error #

You can use the identifier closure.useThis to ignore this error using a comment:

// @phpstan-ignore closure.useThis
codeThatProducesTheError();

You can also use only the identifier key to ignore all errors of the same type in your configuration file in the ignoreErrors parameter:

parameters:
	ignoreErrors:
		-
			identifier: closure.useThis

Rules that report this error #

  • PHPStan\Rules\Functions\ClosureUsesThisRule [1] phpstan/phpstan-strict-rules
  • PHPStan\Rules\Functions\InvalidLexicalVariablesInClosureUseRule [1]

Edit this page on GitHub

Theme
A
© 2026 PHPStan s.r.o.