-
Notifications
You must be signed in to change notification settings - Fork 7.9k
[RFC] Switch expression #5308
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
[RFC] Switch expression #5308
Conversation
184a6e7
to
1b15392
Compare
Hello, can you explain what's difference between return $x switch {
0 => 'Zero',
1 => 'One',
2 => 'Two',
3 => 'Three',
4 => 'Four',
5 => 'Five',
6 => 'Six',
7 => 'Seven',
8 => 'Eight',
9 => 'Nine',
}; and return [
0 => 'Zero',
1 => 'One',
2 => 'Two',
3 => 'Three',
4 => 'Four',
5 => 'Five',
6 => 'Six',
7 => 'Seven',
8 => 'Eight',
9 => 'Nine',
][$x]; ? Because currently I don't see advantage of your proposal over simple array map. |
Your example will execute every arm. return [
0 => expensiveFunction1(),
1 => expensiveFunction2(),
...
][$x]; Furthermore it builds a hash map in memory every time it executes. That is of course given the array isn't constant. |
Indeed. So it's more like return [
0 => fn() => 'Zero',
1 => fn() => 'One',
2 => fn() => 'Two',
...
][$x](); |
I prefer the
I'm ok with losing the |
I agree but as mentioned the syntax is ambiguous. Context-sensitive grammar has not been well accepted in PHP.
That's a nice idea 🙂 |
Almost, you're still missing the It is in fact equivalent to: switch ($x) {
case 0:
$tmp = 'Zero',
break;
case 1:
$tmp = 'One',
break;
...
default:
throw new InvalidArgumentException();
}
return $tmp; It reuses the existing |
1b15392
to
a7c2784
Compare
a7c2784
to
77bd887
Compare
@@ -52,6 +52,7 @@ enum _zend_ast_kind { | |||
ZEND_AST_STMT_LIST, | |||
ZEND_AST_IF, | |||
ZEND_AST_SWITCH_LIST, | |||
ZEND_AST_SWITCH_CASE_COND_LIST, |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
We could actually probably reuse the ZEND_AST_EXPR_LIST
.
@webmozart I found a way to resolve the ambiguity after all. The only downside is that empty switch expressions are disallowed: // This throws a parser error
$x => switch ($y) {}; |
@iluuu1994 Nice! IMHO there's no valid use case for that, so I would expect a parser error to be thrown. |
@@ -0,0 +1,23 @@ | |||
--TEST-- |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This test is useless now.
|
||
?> | ||
--EXPECTF-- | ||
Warning: assert(): assert('foo' switch { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This syntax needs to be updated.
Superseded by #5371. |
Implementation for the coming switch expression RFC.
https://wiki.php.net/rfc/switch_expression