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 Logger
{
/** @phpstan-impure */
public function __construct()
{
echo 'Logger initialized';
}
}
/**
* @phpstan-pure
*/
function createLogger(): Logger
{
return new Logger();
}
Why is it reported? #
A function or method marked as @phpstan-pure must not have side effects and must always return the same result for the same inputs. Instantiating a class with new is considered impure when the constructor is known to have side effects (such as writing to a file, echoing output, or modifying global state). PHPStan reports this when the constructor is explicitly marked as @phpstan-impure.
How to fix it #
If the class constructor is truly side-effect-free, mark it as @phpstan-pure:
<?php declare(strict_types = 1);
class Logger
{
- /** @phpstan-impure */
+ /** @phpstan-pure */
public function __construct()
{
- echo 'Logger initialized';
+ // no side effects
}
}
Or remove the @phpstan-pure annotation from the calling function if it genuinely needs to create objects with impure constructors:
<?php declare(strict_types = 1);
-/**
- * @phpstan-pure
- */
function createLogger(): Logger
{
return new Logger();
}
How to ignore this error #
You can use the identifier impure.new to ignore this error using a comment:
// @phpstan-ignore impure.new
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: impure.new