Error Identifier: closure.unusedUse
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);
function doFoo(string $used, string $unused): void
{
$fn = function () use ($used, $unused) {
echo $used;
};
}
Why is it reported? #
The anonymous function (closure) imports the variable $unused via the use clause, but never references it within the closure body. Importing unused variables into a closure is unnecessary and makes the code harder to understand. It may also indicate a mistake where the variable was intended to be used but was forgotten.
How to fix it #
Remove the unused variable from the use clause:
<?php declare(strict_types = 1);
function doFoo(string $used, string $unused): void
{
- $fn = function () use ($used, $unused) {
+ $fn = function () use ($used) {
echo $used;
};
}
Or use the variable inside the closure if it was intended to be used:
<?php declare(strict_types = 1);
function doFoo(string $used, string $unused): void
{
$fn = function () use ($used, $unused) {
echo $used;
+ echo $unused;
};
}
How to ignore this error #
You can use the identifier closure.unusedUse to ignore this error using a comment:
// @phpstan-ignore closure.unusedUse
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.unusedUse