Re: Strict switch statements
| From: | Theodore Brown | Date: | Fri, 15 Jun 2018 14:54:48 +0000 |
| Subject: | Re: Strict switch statements | ||
| References: | 1 2 3 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-102277@lists.php.net to get a copy of this message | ||
On Thu, Jun 14, 2018 at 4:35 AM, Nikita Popov <nikita.ppv@gmail.com> wrote:
> I think if people want to use strict matching, they'll quite likely want to
> have it on all cases. Something like "strict switch ($expr) {}" or "switch
> strict ($expr) {}" or "switch (strict $expr) {}" or "switch ($expr) strict
> {}" or "switch ($expr) { strict; }" or whatever would be preferable in that
> case.
>
> Additionally, switch has the issue of fall-through behavior, which is
> somewhat unexpected and error prone to many people. It might make sense to
> introduce an entirely new "match" statement that conforms a bit more with
> how switch-like strictures are implemented nowadays. That is, something like
>
> match ($expr) {
> "foo" => {...},
> "bar" | "baz" => {...},
> }
>
> or similar. This might need some more design work to ensure forward
> compatibility with potential future algebraic datatypes etc.
I really like this idea. It's similar to the
match control flow operator
in Rust: https://doc.rust-lang.org/book/second-edition/ch06-02-match.html.
One reason I almost never use the switch statement in PHP (besides the
lack of strict matching) is that it's so verbose. Having to put a break
keyword after every case to avoid fallthrough means that it almost always
requires less code to use if statements instead.
To avoid confusion with union types, I think I would prefer commas between
or conditions instead of a pipe character. Example:
```
match ($expr) {
"foo", "bar" => {echo 'expr is "foo" or
"bar"';},
true => {echo 'expr is true';},
1 => {echo 'expr is 1';},
null => {echo 'expr is null';},
false => {echo 'expr is false';},
default => {echo 'expr is something else';},
}
```