Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Typed local variables #154

Open
thekid opened this issue Feb 12, 2023 · 1 comment
Open

Typed local variables #154

thekid opened this issue Feb 12, 2023 · 1 comment

Comments

@thekid
Copy link
Member

thekid commented Feb 12, 2023

Inspired by https://externals.io/message/119470#119488 and https://wiki.php.net/rfc/local_variable_types

What we would like to achieve

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.

@thekid
Copy link
Member Author

thekid commented Jun 24, 2023

This could also be used to implemented readonly / constant function arguments, as discussed in https://externals.io/message/120615 and https://externals.io/message/120203#120210

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

No branches or pull requests

1 participant