Putting the match expression in constant expressions in PHP 8.0 or 8.1
| From: | tyson andre | Date: | Sat, 08 Aug 2020 00:21:58 +0000 |
| Subject: | Putting the match expression in constant expressions in PHP 8.0 or 8.1 | ||
| Groups: | php.internals | ||
| Request: | Send a blank email to internals+get-111370@lists.php.net to get a copy of this message | ||
Hi internals,
The match expression can be thought of as a much more concise/readable equivalent to chained ternary
operators.
I'm proposing allowing matches in constant expressions when all parts of the match are constant
expressions.
For example, these two class constants would have equivalent behaviors if match expressions were
allowed in constant expressions.
```
class MyClass {
const CONFIG_SETTING = (APP_ENVIRONMENT == 'dev' || APP_ENVIRONMENT ==
'stage') ? 'development-config' :
(APP_ENVIRONMENT == 'prod' ? 'production-config' : null);
const CONFIG_SETTING = match(APP_ENVIRONMENT) {
'dev', 'stage' => 'development-config',
'prod' => 'production-config',
default => null,
};
}
```
https://github.com/php/php-src/pull/5951
implements the main part of the change.
This is mostly for the sake of consistency, since match can be thought of as yet another control
flow primitive that is more readable under some circumstances.
So I had some questions:
1. Should this target 8.0 or 8.1? I'm leaning towards 8.1 since the beta is already out.
2. Are there objections to doing this?
3. Should/shouldn't php enforce that the default arm exists for match *in constant expressions*
(constant expressions can already throw errors when evaluated for various reasons, but
UnhandledMatchError is new)
Thanks,
- Tyson