Loading episodes…
0:00 0:00

How to use php 8 enum

00:00
BACK TO HOME

How to use php 8 enum

10xTeam January 05, 2023 2 min read

Enums (short for “enumerations”) are a new data type in PHP 8 that allows you to define a set of named constants. They are useful for representing a fixed set of values that a variable can take on.

Here is an example of how to use enums in PHP 8:

class Color extends Enum
{
    private const RED = '#ff0000';
    private const GREEN = '#00ff00';
    private const BLUE = '#0000ff';

    public static function RED(): self
    {
        return new self(self::RED);
    }

    public static function GREEN(): self
    {
        return new self(self::GREEN);
    }

    public static function BLUE(): self
    {
        return new self(self::BLUE);
    }
}

$color = Color::RED();
echo $color;  // Outputs: "#ff0000"

In the example above, the Color class extends the Enum class and defines three named constants: RED, GREEN, and BLUE. It also defines three static methods (RED(), GREEN(), and BLUE()) that return new Color objects with the corresponding constant values.

You can use the is() method to check if a Color object is a specific value:

if ($color->is(Color::RED())) {
    echo "The color is red.";
}

You can also use the toArray() method to get an array of all the constants defined in an enum:

$colors = Color::toArray();
print_r($colors);  // Outputs: ["#ff0000", "#00ff00", "#0000ff"]

Enums can also have string or integer values, not just constants. For example:

class Size extends Enum
{
    private const SMALL = 'small';
    private const MEDIUM = 'medium';
    private const LARGE = 'large';

    public static function SMALL(): self
    {
        return new self(self::SMALL);
    }

    public static function MEDIUM(): self
    {
        return new self(self::MEDIUM);
    }

    public static function LARGE(): self
    {
        return new self(self::LARGE);
    }
}

Join the 10xdev Community

Subscribe and get 8+ free PDFs that contain detailed roadmaps with recommended learning periods for each programming language or field, along with links to free resources such as books, YouTube tutorials, and courses with certificates.

Audio Interrupted

We lost the audio stream. Retry with shorter sentences?