int $i= 0;
$i= 'Test'; // Should throw an exception
How it can be implemented
($_w= new class(0) { public function __construct(public int $value) { } }) ? $i= &$_w->value : null;
$i= 'Test'; // Cannot assign string to reference held by property class@anonymous::$value of type int
In the compiler, we could keep of the variables and instead of using references, emit $_i->value everywhere we encounter $i in the current block. This would also allow us to implement readonly local variables (like const in JavaScript):
// readonly int $i= 5;
$_i= new class(5) { public function __construct(public readonly int $value) { } };
// $i++;
$_i->value++; // Cannot modify readonly property class@anonymous::$value
Limitations
We can only use types in the PHP type system, e.g. the above wouldn't work for array<int> for example.
Performance
Using $_i->value instead of $i timed in at 175 milliseconds instead of 127 for 10 million assignments - a very small decrease, which will mostly not be noticed.
Inspired by https://externals.io/message/119470#119488 and https://wiki.php.net/rfc/local_variable_types
What we would like to achieve
How it can be implemented
In the compiler, we could keep of the variables and instead of using references, emit
$_i->value
everywhere we encounter$i
in the current block. This would also allow us to implement readonly local variables (like const in JavaScript):Limitations
We can only use types in the PHP type system, e.g. the above wouldn't work for
array<int>
for example.Performance
Using
$_i->value
instead of$i
timed in at 175 milliseconds instead of 127 for 10 million assignments - a very small decrease, which will mostly not be noticed.