Re: Let's discuss enums!
| From: | Bob Weinand | Date: | Fri, 18 Sep 2015 00:06:50 +0000 |
| Subject: | Re: Let's discuss enums! | ||
| References: | 1 2 3 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-88301@lists.php.net to get a copy of this message | ||
> Am 18.09.2015 um 01:52 schrieb John Bafford <jbafford@zort.net>:
>
> On Sep 17, 2015, at 19:16, Bob Weinand <bobwei9@hotmail.com> wrote:
>>
>>> Am 18.09.2015 um 01:06 schrieb Rowan Collins <rowan.collins@gmail.com>:
>>>
>>> This has come up in passing a few times recently, but I'm not sure there's
>>> ever been a dedicated discussion of it: would it be useful for PHP to have a built-in Enumeration
>>> type, and if so, how should it look?
>>
>> I like enums in general, but I'd like to note that there's already a RFC in draft
>> by Levi:
>>
>> https://wiki.php.net/rfc/enum
>> <https://wiki.php.net/rfc/enum>
>>
>> As far as I know, the RFC is already fairly final and just lacks an implementation.
>>
>> So, I'd consider bikeshedding an actual RFC first.
>
> If we’re bikeshedding, one feature I would really like to see, with typehinting, is warnings
> if all cases of an enum aren’t handled in a switch. So, for example, given our example Weekdays
> enum, if I wrote this code:
>
> switch(Weekday $someWeekday) {
> case Weekday::MONDAY: break;
> case Weekday::TUESDAY: break;
> }
>
> By providing the typehint, I’m indicating that I want to get a warning/error that the switch
> does not cover all enum values. This would be very handy if an enum value is added after initial
> development and someone misses a switch statement in cleanup.
>
> The typehint would also allow generating a warning if someone did something like
>
> switch(Weekday $someWeekday) {
> //case … all the weekdays: break;
> case ‘I am not a Weekday’: echo ‘Generate a fatal error here because string is not a
> Weekday.’;
> }
>
> -John
So, you mean like an implicit
default: throw Error("Unhandled enum value Weekday::FRIDAY");
Possible, but then you also just can add
default: assert(0);
instead of a typehint.
At compile-time won't be really possible, as, when the switch is encountered, the enum might
not yet have been loaded. That's one of the consequences of PHP's lazy inclusion system...
Bob