Re: Inline switch as alternative to nested inline conditional
| From: | Bob Weinand | Date: | Wed, 16 Oct 2019 21:21:32 +0000 |
| Subject: | Re: Inline switch as alternative to nested inline conditional | ||
| References: | 1 2 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-107563@lists.php.net to get a copy of this message | ||
Am 16.10.2019 um 21:19 schrieb Claude Pache <claude.pache@gmail.com<mailto:claude.pache@gmail.com>>:
Le 16 oct. 2019 à 19:11, Bob Weinand <bobwei9@hotmail.com<mailto:bobwei9@hotmail.com>> a écrit :
Am 16.10.2019 um 03:46 schrieb David Rodrigues <david.proweb@gmail.com<mailto:david.proweb@gmail.com>>:
Hello. I like to suggests a discussion about a FR to make possible to
inline switch, as an alternative to nested inline conditionals.
$value = switch (expr()) {
case A1: return A2;
case B1: return B2;
default: return C;
}
Instead of:
$expr = expr();
$value = $expr == A1 ? A2 : ( $expr == B1 ? B2 : C );
Just a discussion to check what do you think.
--
David Rodrigues
Hey David,
what's the concrete advantage of this syntax as opposed to the already possible:
$value = [
A1 => A2,
B1 => B2,
][expr()] ?? C;
there are only differences in edge cases (with floats or with type mixing) … but for the vast
majority of use cases, it is just as powerful as what you proposed.
Bob
One concrete advantage is, when A2 or B2 are complex expressions that are costly to evaluate or that
throw error when given inappropriate input, they are not evaluated needlessly.
—Claude
Most switch values aren't expensive though.
There's always a possibility to prefix with fn() =>:
$value = ([
A1 => fn() => A2,
B1 => fn() => B2,
][expr()] ?? fn() => C)();
For the normal case, this is unneeded though (as in, most of my use cases for "inline
switches" are typically with string operations). Your mileage may vary.
Bob