sajad torkamani

In a nutshell

PHP enums allow you to define a custom type that’s limited to one of a discrete number of possible values.

Enums are a common feature of many programming languages. In PHP, enums are an instance of the Enum class and can be either “pure” or “backed”.

Pure enums

A “pure” enum doesn’t associate any scalar values with any of the cases:

<?php

enum Suit
{
    case Hearts;
    case Diamonds;
    case Clubs;
    case Spades;
}
?>

Backed enums

A “backed” enum associates a scalar with all the enum cases:

<?php

enum Suit: string
{
    case Hearts = 'H';
    case Diamonds = 'D';
    case Clubs = 'C';
    case Spades = 'S';
}
?>

Backed enums can be useful when you need to store values in a database or in an external system because they can be serialised/deserialized using their associated scalar value.

Backed enums implement the BackedEnum interface, which exposes two additional methods:

  • from(int|string): Returns the enum case corresponding to the scalar or throws a ValueError.
  • tryFrom(int|string): Returns the enum case corresponding to the scalar or null if not found.
Tagged: PHP

Leave a comment

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