# Let's discuss enums!

- Thread: https://externals.io/message/88293
- Original archive: https://news-web.php.net/php.internals/88293
- Started by Rowan Collins on 2015-09-17T23:06:57+00:00
- Messages: 47
- Page 1 of 2: messages 1 to 25 (25 per page, add `?page=N` to the URL)
- Next page: https://externals.io/message/88293.md?page=2
- Reply by email to internals@lists.php.net
- More for agents: search with https://externals.io/search.md?q={query} · RFCs at https://externals.io/rfc.md · JSON API at https://externals.io/api · documentation at https://externals.io/llms.txt

---

## #88293 — Rowan Collins — 2015-09-17T23:06:57+00:00

URL: https://externals.io/message/88293#88293

Hi All,

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?

Many other languages have enum types, with varying functionality. The 
central concept is always that there's some declared type with a bunch 
of named constants, but beyond that there's a lot of variability: for 
starters, is it a type of object, a special way of naming integers, or 
an uncomparable type more like booleans and nulls?


Here are my thoughts on what I'd like from a PHP enum - I'm not using 
"should" in a particularly strong sense, it's just a way of framing the 
points of discussion:

1) enums should act like values, not mutable objects; an array-style 
copy-on-write behaviour would be possible, but it feels wrong to me to 
store any state in an enum variable, so just plain immutable would be my 
preference

2) the members of an enum should have a name which is accesible as a 
string, e.g. Weekdays::SUNDAY->getName() == 'SUNDAY'

3) there should be no accessible "value" for a member; the value of 
Weekdays::SUNDAY is simply Weekdays::SUNDAY, not 0 or 7 or 'SUNDAY' (I'm 
thinking that internally, each member would be represented as an object 
pointer, so there's no real benefit to forcing people to number 
everything like some languages do)

4) each enum member should be considered a singleton, in the sense that 
you can't construct or destroy one, only reference them; all possible 
instances would be created as soon as the enum was defined

5) following from (3) and (4), an enum value should compare equal only 
to itself, unlike in C# for instance, where it would be comparable to an 
integer based on its numeric value; similarly it shouldn't be possible 
to cast to or from an enum

6) an enum should be able to have additional fields; these would be 
initialised in the enum's definition; this is inspired by Java and 
Python's ability to pass parameters to the "constructor" of the enum, 
but it feels weird to me for any logic to happen in that constructor 
other than simple assignments, so I'm thinking of a simpler syntax and 
implementation. It also simplifies immutability if no userland code ever 
writes to the properties. There may be an important use case for 
constructor logic I'm missing though?

7) an enum should have default static methods for accessing all the 
members of the enum as an associative array

8) enums should be a first-class type, is_object(Weekdays::SUNDAY) 
should return false, for instance; maybe Weekdays::SUNDAY instanceof 
Weekdays should return true though

9) additional static and instance methods should be definable, bearing 
in mind the immutability constraints already discussed


Given the above, I think we might end up with something like this:

enum Weekdays {
     member MONDAY; // if there are no fields to initalise, the member 
just needs its name declaring
     member TUESDAY ( 2, 'Chewsdae' ); // positional arguments for 
populating fields in the order they are defined; a bit like Java, but 
without the constructor
     member WEDNESDAY { $dayNumber = 3, $sillyName = 'Wed Nose Day' }; 
// or maybe a named-parameter syntax to make things clearer
     member THURSDAY, FRIDAY, SATURDAY, SUNDAY; // don't force people to 
write each entry on its own line; maybe even the "member" keyword is too 
much?

     public $dayNumber, $sillyName; // fields initialised for each member

     public static function getWeekend() {
          return [ self::SATURDAY, self::SUNDAY ];
     }

     public function getZeroIndexedDayNumber() {
          return $this->dayNumber - 1;
     }
}

$today = Weekdays::THURSDAY;
foreach ( Weekdays::getMembers() as $day_name => $day ) {
     echo $day->dayNumber;
     if ( $day == $today ) {
        echo "Today!";
     } else {
        echo $day_name; // equivalently: echo $day->getName();
     }
}

// Do we need a static method to access a member by name, or is this 
good enough?
$favourite_day = Weekdays::getMembers()[ $_GET['fav_day'] ];

So, what are anyone's thoughts? Am I rambling on too much as usual? ;)

Regards,

-- 
Rowan Collins
[IMSoP]

---

## #88296 — Marcio Almada — 2015-09-17T23:16:21+00:00

URL: https://externals.io/message/88293#88296 · In reply to: #88293

Hi,

2015-09-17 20:06 GMT-03:00 Rowan Collins <rowan.collins@gmail.com>:
> Hi All,
>
> 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?
>
> Many other languages have enum types, with varying functionality. The
> central concept is always that there's some declared type with a bunch of
> named constants, but beyond that there's a lot of variability: for starters,
> is it a type of object, a special way of naming integers, or an uncomparable
> type more like booleans and nulls?
>
>
> Here are my thoughts on what I'd like from a PHP enum - I'm not using
> "should" in a particularly strong sense, it's just a way of framing the
> points of discussion:
>
> 1) enums should act like values, not mutable objects; an array-style
> copy-on-write behaviour would be possible, but it feels wrong to me to store
> any state in an enum variable, so just plain immutable would be my
> preference
>
> 2) the members of an enum should have a name which is accesible as a string,
> e.g. Weekdays::SUNDAY->getName() == 'SUNDAY'
>
> 3) there should be no accessible "value" for a member; the value of
> Weekdays::SUNDAY is simply Weekdays::SUNDAY, not 0 or 7 or 'SUNDAY' (I'm
> thinking that internally, each member would be represented as an object
> pointer, so there's no real benefit to forcing people to number everything
> like some languages do)
>
> 4) each enum member should be considered a singleton, in the sense that you
> can't construct or destroy one, only reference them; all possible instances
> would be created as soon as the enum was defined
>
> 5) following from (3) and (4), an enum value should compare equal only to
> itself, unlike in C# for instance, where it would be comparable to an
> integer based on its numeric value; similarly it shouldn't be possible to
> cast to or from an enum
>
> 6) an enum should be able to have additional fields; these would be
> initialised in the enum's definition; this is inspired by Java and Python's
> ability to pass parameters to the "constructor" of the enum, but it feels
> weird to me for any logic to happen in that constructor other than simple
> assignments, so I'm thinking of a simpler syntax and implementation. It also
> simplifies immutability if no userland code ever writes to the properties.
> There may be an important use case for constructor logic I'm missing though?
>
> 7) an enum should have default static methods for accessing all the members
> of the enum as an associative array
>
> 8) enums should be a first-class type, is_object(Weekdays::SUNDAY) should
> return false, for instance; maybe Weekdays::SUNDAY instanceof Weekdays
> should return true though
>
> 9) additional static and instance methods should be definable, bearing in
> mind the immutability constraints already discussed
>
>
> Given the above, I think we might end up with something like this:
>
> enum Weekdays {
>     member MONDAY; // if there are no fields to initalise, the member just
> needs its name declaring
>     member TUESDAY ( 2, 'Chewsdae' ); // positional arguments for populating
> fields in the order they are defined; a bit like Java, but without the
> constructor
>     member WEDNESDAY { $dayNumber = 3, $sillyName = 'Wed Nose Day' }; // or
> maybe a named-parameter syntax to make things clearer
>     member THURSDAY, FRIDAY, SATURDAY, SUNDAY; // don't force people to
> write each entry on its own line; maybe even the "member" keyword is too
> much?
>
>     public $dayNumber, $sillyName; // fields initialised for each member
>
>     public static function getWeekend() {
>          return [ self::SATURDAY, self::SUNDAY ];
>     }
>
>     public function getZeroIndexedDayNumber() {
>          return $this->dayNumber - 1;
>     }
> }
>
> $today = Weekdays::THURSDAY;
> foreach ( Weekdays::getMembers() as $day_name => $day ) {
>     echo $day->dayNumber;
>     if ( $day == $today ) {
>        echo "Today!";
>     } else {
>        echo $day_name; // equivalently: echo $day->getName();
>     }
> }
>
> // Do we need a static method to access a member by name, or is this good
> enough?
> $favourite_day = Weekdays::getMembers()[ $_GET['fav_day'] ];
>
> So, what are anyone's thoughts? Am I rambling on too much as usual? ;)
>
> Regards,
>
> --
> Rowan Collins
> [IMSoP]
>

A kitten is working on that https://wiki.php.net/rfc/enum. Many points
on the linked RFC are compatible to the points you raised so it might
be worth reading before even starting any new proposal.

Regards,
Márcio

---

## #88295 — Bob Weinand — 2015-09-17T23:16:23+00:00

URL: https://externals.io/message/88293#88295 · In reply to: #88293

> Am 18.09.2015 um 01:06 schrieb Rowan Collins <rowan.collins@gmail.com>:
> 
> Hi All,
> 
> 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?
> 
> Many other languages have enum types, with varying functionality. The central concept is always that there's some declared type with a bunch of named constants, but beyond that there's a lot of variability: for starters, is it a type of object, a special way of naming integers, or an uncomparable type more like booleans and nulls?
> 
> 
> Here are my thoughts on what I'd like from a PHP enum - I'm not using "should" in a particularly strong sense, it's just a way of framing the points of discussion:
> 
> 1) enums should act like values, not mutable objects; an array-style copy-on-write behaviour would be possible, but it feels wrong to me to store any state in an enum variable, so just plain immutable would be my preference
> 
> 2) the members of an enum should have a name which is accesible as a string, e.g. Weekdays::SUNDAY->getName() == 'SUNDAY'
> 
> 3) there should be no accessible "value" for a member; the value of Weekdays::SUNDAY is simply Weekdays::SUNDAY, not 0 or 7 or 'SUNDAY' (I'm thinking that internally, each member would be represented as an object pointer, so there's no real benefit to forcing people to number everything like some languages do)
> 
> 4) each enum member should be considered a singleton, in the sense that you can't construct or destroy one, only reference them; all possible instances would be created as soon as the enum was defined
> 
> 5) following from (3) and (4), an enum value should compare equal only to itself, unlike in C# for instance, where it would be comparable to an integer based on its numeric value; similarly it shouldn't be possible to cast to or from an enum
> 
> 6) an enum should be able to have additional fields; these would be initialised in the enum's definition; this is inspired by Java and Python's ability to pass parameters to the "constructor" of the enum, but it feels weird to me for any logic to happen in that constructor other than simple assignments, so I'm thinking of a simpler syntax and implementation. It also simplifies immutability if no userland code ever writes to the properties. There may be an important use case for constructor logic I'm missing though?
> 
> 7) an enum should have default static methods for accessing all the members of the enum as an associative array
> 
> 8) enums should be a first-class type, is_object(Weekdays::SUNDAY) should return false, for instance; maybe Weekdays::SUNDAY instanceof Weekdays should return true though
> 
> 9) additional static and instance methods should be definable, bearing in mind the immutability constraints already discussed
> 
> 
> Given the above, I think we might end up with something like this:
> 
> enum Weekdays {
>    member MONDAY; // if there are no fields to initalise, the member just needs its name declaring
>    member TUESDAY ( 2, 'Chewsdae' ); // positional arguments for populating fields in the order they are defined; a bit like Java, but without the constructor
>    member WEDNESDAY { $dayNumber = 3, $sillyName = 'Wed Nose Day' }; // or maybe a named-parameter syntax to make things clearer
>    member THURSDAY, FRIDAY, SATURDAY, SUNDAY; // don't force people to write each entry on its own line; maybe even the "member" keyword is too much?
> 
>    public $dayNumber, $sillyName; // fields initialised for each member
> 
>    public static function getWeekend() {
>         return [ self::SATURDAY, self::SUNDAY ];
>    }
> 
>    public function getZeroIndexedDayNumber() {
>         return $this->dayNumber - 1;
>    }
> }
> 
> $today = Weekdays::THURSDAY;
> foreach ( Weekdays::getMembers() as $day_name => $day ) {
>    echo $day->dayNumber;
>    if ( $day == $today ) {
>       echo "Today!";
>    } else {
>       echo $day_name; // equivalently: echo $day->getName();
>    }
> }
> 
> // Do we need a static method to access a member by name, or is this good enough?
> $favourite_day = Weekdays::getMembers()[ $_GET['fav_day'] ];
> 
> So, what are anyone's thoughts? Am I rambling on too much as usual? ;)
> 
> Regards,
> 
> -- 
> Rowan Collins
> [IMSoP]

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.

Bob

---

## #88297 — user@domain.invalid — 2015-09-17T23:34:20+00:00

URL: https://externals.io/message/88293#88297 · In reply to: #88293

> 3) there should be no accessible "value" for a member; the value of
> Weekdays::SUNDAY is simply Weekdays::SUNDAY, not 0 or 7 or 'SUNDAY' (I'm
> thinking that internally, each member would be represented as an object
> pointer, so there's no real benefit to forcing people to number
> everything like some languages do)

Well, how are you supposed to serialize an enum value without some sort 
of numerical representation or value? Maybe you could serialize it by
converting the enum to a string representation of its name but that 
wouldn't be efficient and also if a developer refactored its code base
and renamed an enum, when unserializing the data it wouldn't be properly 
assigned. Also other languages don't force you to assign value for an 
enum constants, if I recall correctly languages like C/C++ automatically 
assing an interger value to enumerations in they order they were typed so:

enum BadDays {MONDAY, SUNDAY, THURSDAY=5, SATURDAY}

would be MONDAY = 0, SUNDAY = 1, THURSDAY=5, SATURDAY=6

So assigning a value is optional.

I see the enum's rfc mentions boxing primitive types but that seems to 
not solve what I'm saying here at all.

Enums should be a nice way of grouping constant values without hitting 
on the performance (for everything else use a class). The rfc is 
proposing a nice syntax but it doesn't fully covers 
serialization/unserialization of enumerations.

---

## #88298 — John Bafford — 2015-09-17T23:52:28+00:00

URL: https://externals.io/message/88293#88298 · In reply to: #88295

> 
> > […]
> 
> 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

---

## #88299 — Rowan Collins — 2015-09-17T23:56:47+00:00

URL: https://externals.io/message/88293#88299 · In reply to: #88296

> A kitten is working on thathttps://wiki.php.net/rfc/enum. Many points
> on the linked RFC are compatible to the points you raised so it might
> be worth reading before even starting any new proposal.

Aha, I hadn't seen that, should have thought to search the wiki. Still, 
interesting that we seems to mostly agree on the key decisions, although 
I've gone into more detail about things that he's left as Future Scope, 
which is fair enough.

The main thing I'd change if I was writing it is the implicit "ordinal" 
property; I don't really see the point of insisting that the order I 
write "Red, Green, Blue" has some meaning. On the other hand, I'd give 
much more prominence to the name, e.g. by making values() return an 
associative array. You're much more likely to want to say "the value 
whose name is 'RED'" than "the value I defined first in the list", IMHO.

If you have some kind of initialiser syntax for the values - with or 
without a constructor - you get to have ordinals or explicit values 
(like the Flags example) if you want them, and just names if not:

enum RenewalAction{
     Deny( 0 ),
     Approve( 1 );

     public $ordinal;
}
enum Flags{
     a (1  <<  0),
     b( 1  <<  1),
     c(  1  <<  2),
     d(  1  <<  3 ); public $value; }

enum PimaryColours { RED, GREEN, BLUE }

Regards,

-- 
Rowan Collins
[IMSoP]

---

## #88300 — Rowan Collins — 2015-09-18T00:05:48+00:00

URL: https://externals.io/message/88293#88300 · In reply to: #88297

> Well, how are you supposed to serialize an enum value without some 
> sort of numerical representation or value? Maybe you could serialize 
> it by
> converting the enum to a string representation of its name but that 
> wouldn't be efficient and also if a developer refactored its code base
> and renamed an enum, when unserializing the data it wouldn't be 
> properly assigned.

I don't think serializing to a name is particularly more inefficient 
than serializing to an integer - depending on the internal 
implementation, of course. Or do you mean efficiency in terms of the 
length of the string produced?

Nor do I see it as particularly likely that somebody will rename an enum 
member - that would instantly break all code referring to it anyway. 
They could however change the order of fields without realising that it 
would make any difference, since most access would be of the form 
TypeName::ValueName.

Regards,

-- 
Rowan Collins
[IMSoP]

---

## #88301 — Bob Weinand — 2015-09-18T00:06:50+00:00

URL: https://externals.io/message/88293#88301 · In reply to: #88298

> Am 18.09.2015 um 01:52 schrieb John Bafford <jbafford@zort.net>:
> 
> 
> > […]
> 
> 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

---

## #88302 — Bob Weinand — 2015-09-18T00:15:43+00:00

URL: https://externals.io/message/88293#88302 · In reply to: #88299

> Am 18.09.2015 um 01:56 schrieb Rowan Collins <rowan.collins@gmail.com>:
> 
> 
> > […]
> 
> Aha, I hadn't seen that, should have thought to search the wiki. Still, interesting that we seems to mostly agree on the key decisions, although I've gone into more detail about things that he's left as Future Scope, which is fair enough.
> 
> The main thing I'd change if I was writing it is the implicit "ordinal" property; I don't really see the point of insisting that the order I write "Red, Green, Blue" has some meaning. On the other hand, I'd give much more prominence to the name, e.g. by making values() return an associative array. You're much more likely to want to say "the value whose name is 'RED'" than "the value I defined first in the list", IMHO.
> 
> If you have some kind of initialiser syntax for the values - with or without a constructor - you get to have ordinals or explicit values (like the Flags example) if you want them, and just names if not:
> 
> enum RenewalAction{
>    Deny( 0 ),
>    Approve( 1 );
> 
>    public $ordinal;
> }
> enum Flags{
>    a (1  <<  0),
>    b( 1  <<  1),
>    c(  1  <<  2),
>    d(  1  <<  3 ); public $value; }
> 
> enum PimaryColours { RED, GREEN, BLUE }
> 
> Regards,
> 
> -- 
> Rowan Collins
> [IMSoP]

The reason it is not an associative array is that the names are not important.

But we actually need ordinal(), else we'll end up writing array_search(TheEnum::values(), $value).
It's mainly important for the purpose of serializing/unserializing (manually or internally).

You never should *rely* on the ordinal value of the enum for anything. Enums are supposed to be value-less. It's a type. It's not a value. The only usage of the value is going external.

Also, I honestly think the Flags example is a bad one. (At least as long as we don't have a possibility to typehint combined enums...). If you need that, use class constants. They provide exactly what you need.

Bob

---

## #88303 — Ryan Pallas — 2015-09-18T00:27:45+00:00

URL: https://externals.io/message/88293#88303 · In reply to: #88299

I few questions wrt the rfc: https://wiki.php.net/rfc/enum

> An enum value is only equal to itself.
I'm not sure I agree. How then do I store the enum into a DB and compare it
after reading?
switch($db->query('select role from user where user_id = 123')->fetch()[0])
{
  case UserRole::Admin:
      include 'admin.php';
      break;
  case UserRole::User;
      include 'user.php';
      break;
  default:
      include 'login.php';
      break;
}
Would this not ALWAYS include login if UserRole is an enum (instead of a
final class with constants as I use now, which a switch like this will work
for)?  Is this only possible with the magic value method? In which case I'd
have to check the value method, something like case
UserRole::Admin->ordinal() (or name, or value or whatever)?

>  This means that if the name enum is used for a property, function,
method, class, trait or interface there will now be a parse error instead.
Surely, a property can be named enum, since it can be named other reserved
words, for example?
$ php
<?php
class Foo {
  public $function = 'callMe';
  public $trait = 'useMe';
  public $class = 'instantiateMe';
}
$f = new Foo();
var_dump(get_object_vars($f));

array(3) {
  'function' =>
  string(6) "callMe"
  'trait' =>
  string(5) "useMe"
  'class' =>
  string(13) "instantiateMe"
}


Also, I really like the idea of being able to type hint the enum in the
switch(UserRole) that was mentioned. Not sure I like the idea of an
implicit throw though, consider the UserRole above, I might have 10
different roles, but the current switch is only valid for 5 of those roles.
In this situation, if I add a default: return Auth::NotAuthorized; will
that supress the implicit fall throw? If so, how often will the implicit
throw really be hit? I know we have standards that all case statements must
have default statements, to make sure every case is handled, whether we
foresaw it or not.

---

## #88305 — John Bafford — 2015-09-18T00:35:58+00:00

URL: https://externals.io/message/88293#88305 · In reply to: #88301

> 
> 
> > […]
> 
> 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...

Compile-time might not be possible, true, but at least this would provide for runtime checks, and the benefit of explicitly stating intention is that intention is explicitly stated. Also, it would allow the sort of errors I’m proposing be generated to all be standardized across all applications, which would allow fancy error handlers, such as with Symfony, to offer helpful context-specific suggestions. Also, it’d provide static analyzers additional information by which to provide correctness alerts.

-John

---

## #88306 — Bob Weinand — 2015-09-18T00:42:58+00:00

URL: https://externals.io/message/88293#88306 · In reply to: #88303

> Am 18.09.2015 um 02:27 schrieb Ryan Pallas <derokorian@gmail.com>:
> 
> I few questions wrt the rfc: https://wiki.php.net/rfc/enum
> 
> > […]
> I'm not sure I agree. How then do I store the enum into a DB and compare it
> after reading?
> switch($db->query('select role from user where user_id = 123')->fetch()[0])
> {
>  case UserRole::Admin:
>      include 'admin.php';
>      break;
>  case UserRole::User;
>      include 'user.php';
>      break;
>  default:
>      include 'login.php';
>      break;
> }
> Would this not ALWAYS include login if UserRole is an enum (instead of a
> final class with constants as I use now, which a switch like this will work
> for)?  Is this only possible with the magic value method? In which case I'd
> have to check the value method, something like case
> UserRole::Admin->ordinal() (or name, or value or whatever)?

You could use UserRole::values()[$ordinal] and then compare against that.

> > […]
> method, class, trait or interface there will now be a parse error instead.
> Surely, a property can be named enum, since it can be named other reserved
> words, for example?
> $ php
> <?php
> class Foo {
>  public $function = 'callMe';
>  public $trait = 'useMe';
>  public $class = 'instantiateMe';
> }
> $f = new Foo();
> var_dump(get_object_vars($f));
> 
> array(3) {
>  'function' =>
>  string(6) "callMe"
>  'trait' =>
>  string(5) "useMe"
>  'class' =>
>  string(13) "instantiateMe"
> }

Obvious mistake in the RFC, I just changed it...

> Also, I really like the idea of being able to type hint the enum in the
> switch(UserRole) that was mentioned. Not sure I like the idea of an
> implicit throw though, consider the UserRole above, I might have 10
> different roles, but the current switch is only valid for 5 of those roles.
> In this situation, if I add a default: return Auth::NotAuthorized; will
> that supress the implicit fall throw? If so, how often will the implicit
> throw really be hit? I know we have standards that all case statements must
> have default statements, to make sure every case is handled, whether we
> foresaw it or not.

I'd really put that under Future Scope through. It's not really important to the feature of Enums themselves and always can be added later on.

Bob

---

## #88307 — Bob Weinand — 2015-09-18T00:48:52+00:00

URL: https://externals.io/message/88293#88307 · In reply to: #88305

> Am 18.09.2015 um 02:35 schrieb John Bafford <jbafford@zort.net>:
> 
> > […]
> 
> Compile-time might not be possible, true, but at least this would provide for runtime checks, and the benefit of explicitly stating intention is that intention is explicitly stated. Also, it would allow the sort of errors I’m proposing be generated to all be standardized across all applications, which would allow fancy error handlers, such as with Symfony, to offer helpful context-specific suggestions. Also, it’d provide static analyzers additional information by which to provide correctness alerts.
> 
> -John

Static analyzers etc. all can look at the cases and conclude that the type indeed should have been of a certain Enum. I don't really see a particular advantage here.

And for the run-time checks, just add a default: assert(0); as said. I don't see loads of benefits from this extra syntax.
Also, as said, I'd pretty much prefer that to be separated out in a different RFC as it isn't crucial to the Enum feature itself.

Bob

---

## #88308 — John Bafford — 2015-09-18T00:49:35+00:00

URL: https://externals.io/message/88293#88308 · In reply to: #88302

> 
> 
> > […]
> 
> The reason it is not an associative array is that the names are not important.
> 
> But we actually need ordinal(), else we'll end up writing array_search(TheEnum::values(), $value).
> It's mainly important for the purpose of serializing/unserializing (manually or internally).
> 
> You never should *rely* on the ordinal value of the enum for anything. Enums are supposed to be value-less. It's a type. It's not a value. The only usage of the value is going external.
> 
> Also, I honestly think the Flags example is a bad one. (At least as long as we don't have a possibility to typehint combined enums...). If you need that, use class constants. They provide exactly what you need.
> 
> Bob

Besides providing serialization mapping (or, the equivalent of a __toString() value if the enum is used in a strong context), an important benefit to providing a value for enums would be to allow for changing or deprecating enums. So you might want to say something like:

enum FormEvents {
	PRE_SUBMIT,
	PRE_BIND = PRE_SUBMIT, //deprecated name, provide mapping to new name
}

Another good reason for wanting to provide values is so that you could write code like this:

$eventHandlers = [
	FormEvents::PRE_SUBMIT => function() { … },
	FormEvents::POST_SUBMIT => function() { … },
	...
];

Although maybe the ideal solution here would be to allow for array indexes to have more types than just int and string (so that the array index actually is the enum, not some serialized representation).

-John

---

## #88309 — Ben Scholzen — 2015-09-18T01:15:44+00:00

URL: https://externals.io/message/88293#88309 · In reply to: #88293

> Hi All,
>
> 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?

For what it's worth, there's SplEnum ;)

-- 
Ben Scholzen
http://www.dasprids.de

---

## #88310 — Jefferson Gonzalez — 2015-09-18T02:20:53+00:00

URL: https://externals.io/message/88293#88310 · In reply to: #88300

> I don't think serializing to a name is particularly more inefficient
> than serializing to an integer - depending on the internal
> implementation, of course. Or do you mean efficiency in terms of the
> length of the string produced?

Exactly! Lets say you want to create a MembershipStatus

enum MembershipStatus{
     INACTIVE=0,
     ACTIVE=1
}

It would be more memory/space efficient to store 1 or 0 in a database or 
serialized string, also it would be faster to parse than storing the 
full name, eg (bad serialized example but just to show the idea):

e:16:"MembershipStatus":1:{i:0;}

instead of

e:16:"MembershipStatus":1:{s:8:"INACTIVE";}

> Nor do I see it as particularly likely that somebody will rename an enum
> member - that would instantly break all code referring to it anyway.
> They could however change the order of fields without realising that it
> would make any difference, since most access would be of the form
> TypeName::ValueName.
>
> Regards,
>

The renaming thingy, I'm wouldn't be so sure because IDE's can introduce 
refactoring tools for enumerations that rename all occurrences of an 
enum to another. Unless you are working on a public framework that many 
different people is using, in that case you would restraint from 
renaming the enumerations.

---

## #88312 — Stephen Coakley — 2015-09-18T02:58:57+00:00

URL: https://externals.io/message/88293#88312 · In reply to: #88293

> Hi All,
>
> 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?
>
> Many other languages have enum types, with varying functionality. The
> central concept is always that there's some declared type with a bunch
> of named constants, but beyond that there's a lot of variability: for
> starters, is it a type of object, a special way of naming integers, or
> an uncomparable type more like booleans and nulls?
>
>
> Here are my thoughts on what I'd like from a PHP enum - I'm not using
> "should" in a particularly strong sense, it's just a way of framing the
> points of discussion:
>
> 1) enums should act like values, not mutable objects; an array-style
> copy-on-write behaviour would be possible, but it feels wrong to me to
> store any state in an enum variable, so just plain immutable would be my
> preference
>
> 2) the members of an enum should have a name which is accesible as a
> string, e.g. Weekdays::SUNDAY->getName() == 'SUNDAY'
>
> 3) there should be no accessible "value" for a member; the value of
> Weekdays::SUNDAY is simply Weekdays::SUNDAY, not 0 or 7 or 'SUNDAY' (I'm
> thinking that internally, each member would be represented as an object
> pointer, so there's no real benefit to forcing people to number
> everything like some languages do)
>
> 4) each enum member should be considered a singleton, in the sense that
> you can't construct or destroy one, only reference them; all possible
> instances would be created as soon as the enum was defined
>
> 5) following from (3) and (4), an enum value should compare equal only
> to itself, unlike in C# for instance, where it would be comparable to an
> integer based on its numeric value; similarly it shouldn't be possible
> to cast to or from an enum
>
> 6) an enum should be able to have additional fields; these would be
> initialised in the enum's definition; this is inspired by Java and
> Python's ability to pass parameters to the "constructor" of the enum,
> but it feels weird to me for any logic to happen in that constructor
> other than simple assignments, so I'm thinking of a simpler syntax and
> implementation. It also simplifies immutability if no userland code ever
> writes to the properties. There may be an important use case for
> constructor logic I'm missing though?
>
> 7) an enum should have default static methods for accessing all the
> members of the enum as an associative array
>
> 8) enums should be a first-class type, is_object(Weekdays::SUNDAY)
> should return false, for instance; maybe Weekdays::SUNDAY instanceof
> Weekdays should return true though
>
> 9) additional static and instance methods should be definable, bearing
> in mind the immutability constraints already discussed
>
>
> Given the above, I think we might end up with something like this:
>
> enum Weekdays {
>      member MONDAY; // if there are no fields to initalise, the member
> just needs its name declaring
>      member TUESDAY ( 2, 'Chewsdae' ); // positional arguments for
> populating fields in the order they are defined; a bit like Java, but
> without the constructor
>      member WEDNESDAY { $dayNumber = 3, $sillyName = 'Wed Nose Day' };
> // or maybe a named-parameter syntax to make things clearer
>      member THURSDAY, FRIDAY, SATURDAY, SUNDAY; // don't force people to
> write each entry on its own line; maybe even the "member" keyword is too
> much?

Member is even a little too much IMO. A comma-separated list syntax 
would be better, simply because its shorter and more similar to enum 
syntax on other languages.

>      public $dayNumber, $sillyName; // fields initialised for each member
>
>      public static function getWeekend() {
>           return [ self::SATURDAY, self::SUNDAY ];
>      }
>
>      public function getZeroIndexedDayNumber() {
>           return $this->dayNumber - 1;
>      }
> }
>
> $today = Weekdays::THURSDAY;
> foreach ( Weekdays::getMembers() as $day_name => $day ) {
>      echo $day->dayNumber;
>      if ( $day == $today ) {
>         echo "Today!";
>      } else {
>         echo $day_name; // equivalently: echo $day->getName();
>      }
> }
>
> // Do we need a static method to access a member by name, or is this
> good enough?
> $favourite_day = Weekdays::getMembers()[ $_GET['fav_day'] ];

Not sure if this could be allowed, but simply using name interpolation 
would be better. e.g.:

 > $favourite_day = Weekdays::$_GET['fav_day'];

Similar to $object->$name and nothing to do with StaticClass::$property 
syntax.

> So, what are anyone's thoughts? Am I rambling on too much as usual? ;)
>
> Regards,
>

Is there any interest in enum subtypes? As in, allowing each member to 
also be a class? This would allow algebraic data typing, which would be 
a pretty powerful addition to the language.

-- 
Stephen

---

## #88313 — pajousek@gmail.com — 2015-09-18T07:05:11+00:00

URL: https://externals.io/message/88293#88313 · In reply to: #88293

> Hi All,
>
> 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?
>
> Many other languages have enum types, with varying functionality. The
> central concept is always that there's some declared type with a bunch of
> named constants, but beyond that there's a lot of variability: for starters,
> is it a type of object, a special way of naming integers, or an uncomparable
> type more like booleans and nulls?
>
>
> So, what are anyone's thoughts? Am I rambling on too much as usual? ;)
>
> Regards,
>
> --
> Rowan Collins
> [IMSoP]
>

Hi,

personally, I feel that you should be able to assign numeric value to
each element (and have them implicit if not specified).

This is imho better for serialization (but it can be done with names
as well, yeah) - but more importantly, it also allows usage with
bitwise operators, so you could use them as a "flags" (ie. $weekend =
Days::SATURDAY | Days::SUNDAY).

Regards
Pavel Kouřil

---

## #88314 — Rowan Collins — 2015-09-18T08:42:57+00:00

URL: https://externals.io/message/88293#88314 · In reply to: #88302

>The reason it is not an associative array is that the names are not
>important.
...
>You never should *rely* on the ordinal value of the enum for anything.

I feel like I'm missing something here. In my mind, the only absolute universal about all enum implementations is that you refer to values by constant names - e.g. Weekdays::SUNDAY. The name 'SUNDAY' is as fundamental and unchanging as the name 'Weekdays'.

We rely on names to reference classes and functions all the time, and to serialize properties of an object; so what is it about enums that makes having an integer accessible so important?

I note that Java does supply an ordinal(), but the docs say you should basically never use it.

Regards,
-- 
Rowan Collins
[IMSoP]

---

## #88316 — Rowan Collins — 2015-09-18T10:10:14+00:00

URL: https://externals.io/message/88293#88316 · In reply to: #88310

Jefferson Gonzalez wrote on 18/09/2015 03:20:
> 
> > […]
>
> Exactly! Lets say you want to create a MembershipStatus
>
> enum MembershipStatus{
>     INACTIVE=0,
>     ACTIVE=1
> }
>
> It would be more memory/space efficient to store 1 or 0 in a database 
> or serialized string, also it would be faster to parse than storing 
> the full name, eg (bad serialized example but just to show the idea):
>
> e:16:"MembershipStatus":1:{i:0;}
>
> instead of
>
> e:16:"MembershipStatus":1:{s:8:"INACTIVE";}
>

I would expect it to look more like this:

e:16:"MembershipStatus":8:"INACTIVE"


It seems to me that there are lots of things you could do to be 
efficient - declared object properties could be serialized by their 
ordinal position, rather than listing their names, for instance - but 
that would make the serialization more fragile. It seems to me that 
serializing enum values by order or "value" rather than name is much the 
same thing.


> The renaming thingy, I'm wouldn't be so sure because IDE's can 
> introduce refactoring tools for enumerations that rename all 
> occurrences of an enum to another. Unless you are working on a public 
> framework that many different people is using, in that case you would 
> restraint from renaming the enumerations.

Sure, but it seems more likely that somebody would add an extra value to 
an enum in alphabetical order, thus messing up serialized ordinals, than 
they are to refactor their code base to change the name of one of the 
values.

And if you rename a class or property, serialized objects of that class 
will already break, so having serialized enums break on the same action 
seems perfectly natural, whereas having them silently unserialize to the 
wrong value because you changed the ordinal positions of the values 
seems rather dangerous.

Regards,
-- 
Rowan Collins
[IMSoP]

---

## #88324 — Levi Morrison — 2015-09-18T14:11:21+00:00

URL: https://externals.io/message/88293#88324 · In reply to: #88298

> 
> > […]
>
>
> 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).

---

## #88325 — Levi Morrison — 2015-09-18T14:21:53+00:00

URL: https://externals.io/message/88293#88325 · In reply to: #88313

> 
> > […]
>
> Hi,
>
> personally, I feel that you should be able to assign numeric value to
> each element (and have them implicit if not specified).
>
> This is imho better for serialization (but it can be done with names
> as well, yeah) - but more importantly, it also allows usage with
> bitwise operators, so you could use them as a "flags" (ie. $weekend =
> Days::SATURDAY | Days::SUNDAY).

In my opinion this is the least valuable form of enums that exists in
any language I am aware of. However I was careful in the RFC to not
prevent this from being a possibility. I would much, much prefer enums
that are more like Rust's, Haskell's or Swift's. It's worth noting
Swift has at least three different kinds of enums, one of which would
allow the kind of behavior you are wanting.

---

## #88326 — Bob Weinand — 2015-09-18T14:23:35+00:00

URL: https://externals.io/message/88293#88326 · In reply to: #88314

> Am 18.09.2015 um 10:42 schrieb Rowan Collins <rowan.collins@gmail.com>:
> 
> 
> > […]
> ...
> > […]
> 
> I feel like I'm missing something here. In my mind, the only absolute universal about all enum implementations is that you refer to values by constant names - e.g. Weekdays::SUNDAY. The name 'SUNDAY' is as fundamental and unchanging as the name 'Weekdays'.
> 
> We rely on names to reference classes and functions all the time, and to serialize properties of an object; so what is it about enums that makes having an integer accessible so important?
> 
> I note that Java does supply an ordinal(), but the docs say you should basically never use it.
> 
> Regards,
> -- 
> Rowan Collins
> [IMSoP]

Well, I think we should *either* have an ordinal *or* a name.
But not both.

Currently, after thinking about it, I'm in favor of just a name. And no ordinal.
Having both is, I think, unnecessary.

Bob

---

## #88328 — Anthony Ferrara — 2015-09-18T14:42:44+00:00

URL: https://externals.io/message/88293#88328 · In reply to: #88324

Levi et al,


> 
> > […]
>
> 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).

This is basically pattern matching. And while I'd LOVE to see support
for it in PHP, I think it's a bit off-topic here. Perhaps a new thread
could be opened for it (or ideally a RFC)...?

As far as enums, I wonder if they would be necessary if we supported
algebraic types, since you could define an "enum" as a virtual type:

const MONDAY = 0;
const TUESDAY = 1;
const WEDNESDAY = 2;
const THURSDAY = 3;
const FRIDAY = 4;
use MONDAY | TUESDAY | WEDNESDAY | THURSDAY | FRIDAY as WEEKDAY;

function foo(WEEKDAY $day) {
    // must be an integer 0-4, or castable to 0-4 unless strict_types is on.
}

Just a thought...

Anthony

---

## #88329 — Rowan Collins — 2015-09-18T14:48:24+00:00

URL: https://externals.io/message/88293#88329 · In reply to: #88326

Bob Weinand wrote on 18/09/2015 15:23:
> Well, I think we should*either*  have an ordinal*or*  a name.
> But not both.
>
> Currently, after thinking about it, I'm in favor of just a name. And no ordinal.
> Having both is, I think, unnecessary.

Yeah, that was my instinct. It's a bit like surrogate keys on database 
tables - if your table has a natural Primary Key, there's no need to add 
an auto-increment field. :)

And the name kind of has to exist anyway, or you can't reference the 
enum value at all. You could make it inaccessible, but then not being 
able to get a string representation for debugging, or to do a dynamic 
Weekdays::getByName($_GET['day']), would be annoying.

Regards,
-- 
Rowan Collins
[IMSoP]

---

Next page: https://externals.io/message/88293.md?page=2
