Re: [PHP-DEV] [RFC] switch expression

This is only part of a thread. view whole thread
  109299
March 25, 2020 16:21 rowan.collins@gmail.com (Rowan Tommins)
On Wed, 25 Mar 2020 at 15:29, Ilija Tovilo 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]
  109301
March 25, 2020 16:28 ilija.tovilo@me.com (Ilija Tovilo)
Hi Rowan

> 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:
I agree. The iffy part would be recognizing if the case expression should be equated to the switch input or evaluated on its own. That is still something we could address in a later RFC for both the statement and expression. Regards
  109306
March 25, 2020 18:24 php@manuelcanga.dev (Manuel Canga)
Hi, internals,


 ---- En mié, 25 mar 2020 17:21:29 +0100 Rowan Tommins collins@gmail.com> escribió ----
 > On Wed, 25 Mar 2020 at 15:29, Ilija Tovilo 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'
 > };

In this case, you can also do:

$result =  [
    1 => 'hello',
    2 => 'hi',
    3 => 'goodbye'
 ][$this->foo($bar)];

With syntax very similar to proposed switch but this is using array.

Regards
 --
Manuel Canga