Re: [RFC] Enumerations, Round 2
| From: | Larry Garfield | Date: | Thu, 31 Dec 2020 17:15:41 +0000 |
| Subject: | Re: [RFC] Enumerations, Round 2 | ||
| References: | 1 2 3 4 5 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-112700@lists.php.net to get a copy of this message | ||
On Thu, Dec 31, 2020, at 6:53 AM, Rowan Tommins wrote:
> On 30/12/2020 21:24, Aleksander Machniak wrote:
> > My argument is that, from an end-user perspective, I don't really see
> > why Unit and Scalar enums have to have different "API" at this point..
> > I'm talking about ":string"/":int" in the enum definiton as well
> > as
> > ->value and ->from().
>
>
> My personal opinion is that for many enums, explicitly not having a
> scalar representation is a good thing.
>
> This is basically similar to my opinion of __toString() etc: if you have
> *multiple* ways to convert something to/from a scalar, blessing one of
> them as "default" is arbitrary and confusing.
>
> For example:
>
> enum BookingStatus {
> case PENDING;
> case CONFIRMED;
> case CANCELLED;
>
> public function getId() {
> return match($this) {
> self::PENDING => 1,
> self::CONFIRMED => 2,
> self::CANCELLED => 3,
> };
> }
> public function getCode() {
> return match($this) {
> self::PENDING => 'PEN',
> self::CONFIRMED => 'CON',
> self::CANCELLED => 'CAN',
> };
> }
> public function getEnglishDescription() {
> return match($this) {
> self::PENDING => 'Pending Payment',
> self::CONFIRMED => 'Confirmed',
> self::CANCELLED => 'Cancelled',
> };
> }
> }
That is similar to our reasoning. It creates a foot-gun situation where someone could get in the
habit of assuming that an enum always has a *reasonable* and *logical* and thus *reliable* string
equivalent, when not all enums will have string equivalents that it's reasonable and logical to
use. So, one less foot gun.
Also, one of the extensions planned, as noted, is ADTs/tagged unions. Those could not have a
primitive equivalent, since they're not singletons.. Keeping UnitEnum and ScalarEnum separate
allows us to later add TaggedEnum (or similar) that also extends UnitEnum, but not ScalarEnum.
--Larry Garfield