Enums in PHP

Enumerations are a restricting layer on top of classes and class constants, intended to provide a way to define a closed set of possible values for a type.

Simple Example:

enum Status
{
    case DRAFT;
    case PUBLISHED;
    case ARCHIVED;
    
    public function color(): string
    {
        return match($this) 
        {
            Status::DRAFT => 'grey',   
            Status::PUBLISHED => 'green',   
            Status::ARCHIVED => 'red',   
        };
    }
}
$status = Status::ARCHIVED;
$status->color(); // 'red'

Using self

enum Status
{
    // …
    
    public function color(): string
    {
        return match($this) 
        {
            self::DRAFT => 'grey',   
            self::PUBLISHED => 'green',   
            self::ARCHIVED => 'red',   
        };
    }
}

Backed Enums

Enum values are represented by objects internally, but you can assign a value to them if you want to; this is useful for eg. serializing them into a database.

enum Status: string
{
    case DRAFT = 'draft';
    case PUBLISHED = 'published';
    case ARCHIVED = 'archived';
}

source: https://stitcher.io/blog/php-enums

Simple Project Using Enums

https://github.com/b1ink0/PHP-Learning-Projects/tree/php-enums

«
»

Leave a Reply

Your email address will not be published. Required fields are marked *