Re: [RFC] switch expression

From: Date: Thu, 02 Apr 2020 17:28:57 +0000
Subject: Re: [RFC] switch expression
References: 1  Groups: php.internals 
Request: Send a blank email to internals+get-109516@lists.php.net to get a copy of this message
Larry Garfield wrote:
On Sun, Mar 29, 2020, at 4:04 PM, Ilija Tovilo wrote: What you're proposing is a language construct for an *expression*, which evaluates depending on internal logic to a different value. Those are sufficiently distinct that I agree they should have distinct keywords. Plus, the internal syntax is non-trivial to switch back and forth between (break vs not, etc.), so it is misleading for people to present them as two slight variants on the same thing; they're really quite distinct, and that's OK. My recommendation would be to just borrow Rust's keyword: $result = match ($var) { $expression => $expression; $expression => $expression; $expression => $expression; default => $expression; }
I would tend to side with this. The way I'd interpret this is that the provided value is matched against the value of each expression, which also means arbitrary comparisons may be used without additional syntax or special cases, as has been mentioned in this thread: $temp=get_temperature(); $phase = match(true) { $temp<0 => "Ice", $temp>=0 && $temp<=100 => "Water", $temp>100 => "Steam" } I also agree that we should keep this as an expression, not extending it to be a statement as well. Keep it simple. Should we want to use it as a statement at a later point, that would be possible to add. I also like the exhaustive check, so that the following would give an error (and could be found using static analysis) about not handling other values than 1-3: $result = match($x) // int { 1 => ..., 2 => ..., 3 => ... } Having a new keyword like this opens the door to further changes that moves it away from the way switch works, such as pattern matching and destructuring. Regards, Terje

« previous php.internals (#109516) next »