Skip to content

without use native_typesnumeric variable stored as php::Var #85

Description

@jefyokta

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.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions