Re: Let's discuss enums!

From: Date: Fri, 18 Sep 2015 14:11:21 +0000
Subject: Re: Let's discuss enums!
References: 1 2 3  Groups: php.internals 
Request: Send a blank email to internals+get-88324@lists.php.net to get a copy of this message
On Thu, Sep 17, 2015 at 5:52 PM, John Bafford <jbafford@zort.net> wrote: > 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.’; > } I've looked into this but not in the same syntax you've provided. I was exploring a match construct that has different semantics: match ($foo) { case Weekday::Monday: { echo "Monday"; } // it is not possible to fall-through with match/case case Weekday::Tuesday: echo Monday; // single expression doesn't need braces } // if it hits the end without a match a runtime error will be emitted I think this fits into the dynamic behavior of PHP a little better than forcing a case for each enum value at compile-time, even if it was possible (I suspect it is not).

« previous php.internals (#88324) next »