Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[PHP] Add option to generate native PHP 8.1 enums #8513

Open
Manueljlin opened this issue Jan 31, 2025 · 0 comments
Open

[PHP] Add option to generate native PHP 8.1 enums #8513

Manueljlin opened this issue Jan 31, 2025 · 0 comments

Comments

@Manueljlin
Copy link

Manueljlin commented Jan 31, 2025

PHP 8.1 added native enums, so instead of having

class SituationType
{
    const Unknown = 0;
    const SecurityAlert = 1;
    const EmergencyServicesCall = 2;
    const PoliceActivity = 3;
    const PoliceOrder = 4;
    const Fire = 5;
    const CableFire = 6;
    //...

    private static $names = array(
        SituationType::Unknown=>"Unknown",
        SituationType::SecurityAlert=>"SecurityAlert",
        SituationType::EmergencyServicesCall=>"EmergencyServicesCall",
        SituationType::PoliceActivity=>"PoliceActivity",
        SituationType::PoliceOrder=>"PoliceOrder",
        SituationType::Fire=>"Fire",
        SituationType::CableFire=>"CableFire",
        //...
    );

    public static function Name($e)
    {
        if (!isset(self::$names[$e])) {
            throw new \Exception();
        }
        return self::$names[$e];
    }
}

SituationType::Name(e: SituationType::CableFire); // "CableFire"
SituationType::CableFire; // 6

it's now possible to do

enum SituationType : int
{
    case Unknown = 0;
    case SecurityAlert = 1;
    case EmergencyServicesCall = 2;
    case PoliceActivity = 3;
    case PoliceOrder = 4;
    case Fire = 5;
    case CableFire = 6;
    //...
}

SituationType::CableFire->name; // "CableFire"
SituationType::CableFire->value; // 6

foreach (Status::cases() as $case) {
    echo "name {$case->name}, value {$case->value}\n";
}

this might be worth looking into? php 8.0 is already eol

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant