On 30/07/2021 18:24, Kirill Nesmeyanov wrote:
enum ErrorGroup: int
{
     case NOTICE = 0;
     case WARNING = 10;
     case ERROR = 20;
}
enum ErrorCode: int
{
     case UNKNOWN = 0;
    case A = ErrorGroup::NOTICE + 1;
     case B = ErrorGroup::NOTICE + 2;
     case С = ErrorGroup::NOTICE + 3;
     case D = ErrorGroup::WARNING + 1;
     case E = ErrorGroup::ERROR + 1;
}


As I say, those are not enums in the way the current feature defines "enum".

An enum, as implemented in the current 8.1 alphas, is not just a special kind of constant, even if it has an integer or string associated. Every enum is its own type (essentially a class), and every value is a distinct value of that type (essentially an instance), which compares equal only to itself.

var_dump(ErrorGroup::WARNING); // enum(ErrorGroup::WARNING);
var_dump(ErrorGroup::WARNING == 10); // bool(false)
var_dump(get_class(ErrorGroup::WARNING)); // string(10) "ErrorGroup"


There are languages where enums are just fancy names for integers, and you can write things like "if ( ErrorCode::D >= ErrorGroup::WARNING )". In my opinion, that makes enums much less useful, because it means you can also write nonsensical things like "if ( Month::JANUARY <= Day::WEDNESDAY )".

If you want to pass around an integer, but have a convenient name for it, you can still use a class constant. The main value of native enums, in my opinion, is being able to write strongly typed code saying "this accepts a value of type ErrorGroup, and nothing else".

Regards,

--
Rowan Tommins
[IMSoP]

--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: https://www.php.net/unsub.php

Reply via email to