> Le 17 déc. 2020 à 17:23, Sara Golemon <poll...@php.net> a écrit :
>
> On Wed, Dec 16, 2020 at 6:50 PM someniatko <somenia...@gmail.com> wrote:
>>
>> `match` is an expression, where as if-else construction is not. This
>> allows for combining it with a potential future feature of single line
>> functions and methods. For example (hypothetical syntax is used):
>>
>> ```
>> $getNumber = fn(int $number) => match {
>> $number < 0 => NumberKind::NEGATIVE,
>> $number == 0 => NumberKind::ZERO,
>> $number > 0 => NumberKind::POSITIVE,
>> };
>> ```
>>
>
> That does read attractively, yes. This is the example that should have
> been offered first as it shows the expression nature shining.
>
> To contrast that with what would be possible now in an expressive
> functional form:
>
> $getNumber = fn(int $number) => [
> -1 => NumberKind::NEGATIVE,
> 0 => NumberKind::ZERO,
> 1 => NumberKind::POSITIVE,
> ][$number <=> 0];
>
> The match form *certainly* reads more naturally than the spaceship indexing
> form even though both take up equal space.
>
> -Sara
If you mean a version of `if` that works in expressions, there already exists a
standard operator for that. Once its historical associativity goof is
definitely fixed, you will be able to write:
```
$getNumberKind = fn(int $number) =>
$number > 0 ? NumberKind::POSITIVE :
$number == 0 ? NumberKind::ZERO :
$number < 0 ? NumberKind::NEGATIVE :
throw new \TypeError;
```
There is a semantic advantage of `match` over `? : `, though, namely its
exhaustivity: You don’t need to add a “panic” default case in order to catch
logic errors.
—Claude
--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: https://www.php.net/unsub.php