-
-
Notifications
You must be signed in to change notification settings - Fork 946
Description
Feature request
When using dynamicConstantNames, PHPStan allows the constant value to change, but not the type. This can be overly restrictive when the nominal value is a type that only permits a single value, e.g. null or array{}, since it defeats the purpose of declaring it as dynamic.
I'm not sure how to best solve this problem. Perhaps it could be done in a generic way with an optional type specification in the dynamicConstantNames configuration. Or maybe, for specific singular-value types, a sensible type mutation could be allowed (e.g. null -> mixed, array{} -> array<mixed>).
Examples
I don't know how to add configuration options to https://phpstan.org/try, so I'll just provide a few code snippets here.
Given the following configuration:
parameters:
dynamicConstantNames:
- FOO We can see that if the nominal value of FOO is an empty array (which is a reasonable default for a dynamic constant array), PHPStan assumes it will always be an empty array:
const FOO = [];
FOO !== [];Strict comparison using !== between array{} and array{} will always evaluate to false.
The same is true when the nominal value is null:
const FOO = null;
FOO !== null;Strict comparison using !== between null and null will always evaluate to false.
It seems less likely that supporting more generic type mutation would be widely useful, but it may be worthwhile to consider. For example, we cannot change a constant int to a string (or vice versa):
const FOO = 1;
FOO === 'bar';Strict comparison using === between int and 'bar' will always evaluate to false.
Did PHPStan help you today? Did it make you happy in any way?
I've spent the past few years modernizing a 20+ year old PHP project. It simply wouldn't be possible without great tools like PHPStan to give me peace of mind and incremental goals to strive for. Thank you to everyone who helps to make PHPStan possible!