Enums in PHP

Our enum type ServerState has an underlying int type.

class ServerState {
    const StateIdle = 0;
    const StateConnected = 1;
    const StateError = 2;
    const StateRetrying = 3;

    private static $stateNames = [
        self::StateIdle => "idle",
        self::StateConnected => "connected",
        self::StateError => "error",
        self::StateRetrying => "retrying",
    ];

    public static function toString($state) {
        return self::$stateNames[$state];
    }
}

The possible values for ServerState are defined as constants. This approach automatically provides successive constant values 0, 1, 2, and so on.

By providing a toString method, values of ServerState can be printed out or converted to strings.

function transition($state) {
    switch ($state) {
        case ServerState::StateIdle:
            return ServerState::StateConnected;
        case ServerState::StateConnected:
        case ServerState::StateRetrying:
            return ServerState::StateIdle;
        case ServerState::StateError:
            return ServerState::StateError;
        default:
            throw new Exception("Unknown state: " . ServerState::toString($state));
    }
}

The transition function emulates a state transition for a server. It takes the existing state and returns a new state.

function main() {
    $ns = transition(ServerState::StateIdle);
    echo ServerState::toString($ns) . PHP_EOL;

    $ns2 = transition($ns);
    echo ServerState::toString($ns2) . PHP_EOL;
}

main();

In the main function, we demonstrate state transitions starting from StateIdle.

$ php enums.php
connected
idle

If we run the program using PHP, it will output connected followed by idle.