Error Identifier: new.dateTimeImmutable
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);
$date = new DateTimeImmutable('this is not a date');
Why is it reported? #
The DateTimeImmutable constructor is being called with a date string that PHP cannot parse. When an invalid date string is passed, DateTimeImmutable::__construct() produces an error. PHPStan detects constant string arguments that will cause a parsing failure at runtime and reports them at analysis time.
How to fix it #
Provide a valid date string:
<?php declare(strict_types = 1);
-$date = new DateTimeImmutable('this is not a date');
+$date = new DateTimeImmutable('2024-01-15');
Or use DateTimeImmutable::createFromFormat() for predictable parsing of non-standard formats:
<?php declare(strict_types = 1);
-$date = new DateTimeImmutable('this is not a date');
+$date = DateTimeImmutable::createFromFormat('Y/m/d', '2024/01/15');
How to ignore this error #
You can use the identifier new.dateTimeImmutable to ignore this error using a comment:
// @phpstan-ignore new.dateTimeImmutable
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: new.dateTimeImmutable
Rules that report this error #
- PHPStan\Rules\DateTimeInstantiationRule [1]