Re: [RFC] switch expression
| From: | Rowan Tommins | Date: | Wed, 25 Mar 2020 16:21:29 +0000 |
| Subject: | Re: [RFC] switch expression | ||
| References: | 1 2 3 4 5 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-109299@lists.php.net to get a copy of this message | ||
On Wed, 25 Mar 2020 at 15:29, Ilija Tovilo <ilija.tovilo@me.com> wrote:
> I don't think this would add any significant benefit over:
>
> ```php
> $x = true switch {
> $x !== null && $x < 5 => ...
> }
> ```
>
The problem with that is that it requires a temporary variable to be
switched on. If I want to switch on, say, a method call, I can write this
for equality:
$result = $this->foo($bar) switch {
1 => 'hello',
2 => 'hi',
3 => 'goodbye'
};
For inequalities, the switch(true) version looks something like this (the
parentheses would probably be optional, but I'd personally use them for
readability):
$temp = $this->foo($bar);
$result = true switch {
($temp <= 1) => 'hello',
($temp == 2) => 'hi',
default => 'goodbye'
}
Using $$ to mean "value tested" would mean you could get rid of the temp
variable, and just write this:
$result = $this->foo($bar) switch {
($$ <= 1) => 'hello',
($$ == 2) => 'hi',
default => 'goodbye'
};
I've also previously thought about specifying an operator for switch
statements, which could be used with expressions as well, e.g.
$result = $this->foo($bar) switch <= {
1 => 'hello',
2 => 'hi',
default => 'goodbye'
};
Again, though, this is something that could be added to switch statements
and expressions together, as a separate RFC.
Regards,
--
Rowan Tommins
[IMSoP]