php-src icon indicating copy to clipboard operation
php-src copied to clipboard

enums: is_case() function

Open ghost opened this issue 4 years ago • 4 comments

Description

There is currently no way to determine if an expression or variable is of type "enum" (or I don't know how).

Since "enum" is a new data type, it would be desirable for there to be a function to know if an expression or variable is a case of an enumeration.

Such a function could be:

is_case()
is_enum()
is_enum_case()
is_enumcase()

ghost avatar Dec 06 '21 16:12 ghost

AFAIK, that has been discussed an rejected in favor of doing an instanceof check (potentially combined with an is_object check). @Crell, can you please clarify?

cmb69 avatar Dec 06 '21 16:12 cmb69

https://externals.io/message/112626

It looks like there was originally an "is_enum" function on the table to support this but it was a bit too broad: there were concerns that functionality to check if "Foo::Bar" is an enum was a problem because of the automatic autoloading for a string, so that was then moved into a more dedicated enum_exists function. The support for checking if a value was an enum doesn't seem to have survived the process.

You can currently check for the UnitEnum interface using $value instanceof UnitEnum - as long as you have in your head that enum values are actually objects. Which is why I think adding an "is_enum" is actually a bit odd. It certainly makes sense on the surface, but it's not like enums are a new primitive type, and there aren't "is_traversable"[^1] or "is_throwable" functions to set a precedent for checking special interfaces.

Is there a common use case for checking if something is an enum in a general sense? Wouldn't most usages be for checking against a particular enum type (if not already type-hinted), in which case instanceof is already the answer?

[^1]: There is is_iterable but that's because it supports arrays too.

damianwadley avatar Dec 06 '21 17:12 damianwadley

$value instanceof UnitEnum is indeed the intended way to check whether something is an instance of an enum case. I'm going to explicitly decline the addition of a function that does the same thing.

nikic avatar Dec 06 '21 18:12 nikic

Sorry, I was unaware of the existence of the UnitEnum interface. Thanks for your clarification.

ghost avatar Dec 06 '21 18:12 ghost