> On Oct 15, 2019, at 11:33 PM, Michał Brzuchalski
> <[email protected]> wrote:
>
> I have an RFC in draft for that and planning to finish it soon together
> with some syntax optimisations - you can see it at
> https://wiki.php.net/rfc/switch-expression-and-statement-improvement
>
> Cheers,
> Michał Brzuchalski
In an earlier message I said I would return to comment on some concerns I have
with the RFC.
In general, I would appreciate having a way to express a "switch" in an
expression much like how you can express an "if" with the ternary operator.
However, the specifics of your suggestion give me pause.
Also, some of my concerns are contradictory to each other which I will admit in
advance.
1. I am a strong believer in language design that facilitates refactoring. But
your syntax would make refactoring from an existing switch harder than it would
need to be if the syntax more closely matched the existing switch.
In your proposal you replace colons (:) with fat arrows (=>) which has no
perceptible benefit, at least not for me:
$say = switch (date("w")):string {
case 0 => "weekend!";
case 1, 2, 3, 4, 5 => "weekday :(";
case 6 => "weekend!";
};
The same logic in today's PHP:
switch (date("w")) {
case 0:
$say = "weekend!";
break
case 1, 2, 3, 4, 5:
$say = "weekday :(";
break
case 6:
$say = "weekend!";
};
It would be easier to manually refactor if mostly the same syntax was used,
e.g. with colons (") vs. fat arrows (=>):
$say = switch (date("w")):string {
case 0: "weekend!";
case 1, 2, 3, 4, 5: "weekday :(";
case 6: "weekend!";
};
So if I had a vote I would vote likely against your RFC with the fat arrows but
for it if you changed it to use colons instead.
2. However, I find the above more verbose than would be ideal, and I would like
an optional equivalent of the ternary operator, e.g. both a verbose option and
a terse option. I said optional above because — unlike the stated preferences
of others here on this list — I celebrate having multiple ways to accomplish
the same task because some approaches fit a given use-case better than other
approaches.
What might a terse option look like? Maybe this, although I might have missed
conflicts to the existing language:
$say = date("w"):string ???
0: "weekend!";
1, 2, 3, 4, 5: "weekday; :(";
6: "weekend!";
$default;
I will say, one huge benefit to an inline switch would be allowing for switch
logic without requiring a `break` (or an explicit `fallthrough`) and without
any backward compatibility concerns, at least for some use-cases.
-Mike