Consider the following code:
<?phpdeclare(strict_types=1);
functionmain()
{
$x = 42;
$x = [1, 2];
}This compiles without any error and value changed
However, when using native_types:
<?phpdeclare(strict_types=1);
usenative_types;
functionmain()
{
$x = 42;
$x = [1, 2];
}the compiler reports:
Fatal error: Cannot re-assign `$x` from `php::Array` to `php::Int`# is not it should be int to array?
Does native_types need to be enabled to strictly lock the inferred type of numeric variables?
Reference:
| |
| protectedfunctiongetNativeType(string$type): string |
| { |
| if ($type === Type::INT && $this->bigintTypes) { |
| return Type::BIGINT; |
| } |
| if ($type === Type::FLOAT && $this->decimalTypes) { |
| return Type::DECIMAL; |
| } |
| return$this->nativeTypes ? $type : Type::VAR; |
| } |
| |
| protectedfunctionconvertExprFromType(string$type, string$expr): string |
When native_types is not enabled, numeric types are converted to php::Var. This means that a variable initially assigned a numeric value can subsequently be reassigned to a different type:
$x = 42; // php::Var$x = [1, 2]; // allowed
With native_types, the numeric type is preserved:
$x = 42; // php::Int$x = [1, 2]; // compile-time error
This makes me wonder whether this is the intended behavior. Since variables inferred as string, array, and object cannot be reassigned to a different type, shouldn't numeric variable type inference also strictly preserve the inferred type by default?
Requiring native_types for numeric types seems inconsistent with the behavior of other inferred types. Without native_types, numeric values are converted to php::Var, allowing a variable initially assigned a numeric value to be reassigned to an incompatible type.
Consider the following code:
This compiles without any error and value changed
However, when using
native_types:the compiler reports:
Does
native_typesneed to be enabled to strictly lock the inferred type of numeric variables?Reference:
typephp/src/Parser/TypeConversionTrait.php
Lines 220 to 232 in 87c7eda
When
native_typesis not enabled, numeric types are converted tophp::Var. This means that a variable initially assigned a numeric value can subsequently be reassigned to a different type:With
native_types, the numeric type is preserved:This makes me wonder whether this is the intended behavior. Since variables inferred as
string,array, andobjectcannot be reassigned to a different type, shouldn't numeric variable type inference also strictly preserve the inferred type by default?Requiring
native_typesfor numeric types seems inconsistent with the behavior of other inferred types. Withoutnative_types, numeric values are converted tophp::Var, allowing a variable initially assigned a numeric value to be reassigned to an incompatible type.