If PHPStan complains, that's because the static analysis (which does not execute the code) cannot determine the types properly. As Carbon extends DateTime
, the PHP documentation can help for this method call:
Returns a new DateTime instance or false on failure.
So, to ensure that the code is sound in terms of static analysis, you need to split it up:
$object = Carbon::createFromFormat('Y-m-d H:i:s', '2021-10-01T00:01:00');
if (!$object instanceof Carbon) {
throw new RuntimeException('could not parse date');
}
$object->toDateTime();
The difference: now, PHPStan can safely assume that $object
is of type Carbon
when toDateTime()
is called
As others pointed out: running that code would also yield an error, as the date format you try to parse from and the input date do not match. But that is out of scope for PHPStan, which does not execute the code
createFromFormat()
fails, probably returning false.Y-m-d H:i:s
versus2021-10-01T00:01:00
. Your format has a space; your string has a T instead. Your date string doesn't match your expected format.