Enums in PHP 8

Adrian Voicu
2 min readJan 17, 2024

Enumerations or “Enums” allow us to define a new type of data with a finite number of possible values (as an example, the boolean values are of enum type because they can only by true or false). The main source for this article is a video material that appeared on the YouTube channel Program with Gio (https://www.youtube.com/@ProgramWithGio). I recommend you go there and see a lot of quality videos on programming with PHP.

Enum is a singleton type of object (this means that it cannot be extended or instantiated).

<?php
enum InvoiceStatus
{
case Pending;
case Paid;
case Void;
case Failed;
}

Pure enums vs backed enums

A backed enum has values for the respective objects. In order to create a backed enum, it is necessary to use the type hinting for the return of the Enum (string or integer):

<?php
enum InvoiceStatus: int
{
case Pending = 0;
case Paid = 1;
case Void = 2;
case Failed = 3;
}

There is no possibility to combine the types of backed enumes; you cannot create some sort of hybrid enum (cu case-uri pure și cu case-uri backed) or enums that can return strings and/or integers in the same time.

print InvoiceStatus::Pending->value;
print InvoiceStatus::Pending->name;

We can access all the cases using the static method cases():

print InvoiceStatus::cases();

Accessing the values of a backed enum

We can access values in both directions. In our example, we can return the item name (Failed) using the value (3). We do this using the static methods from() (which returns an exception if the value does not exist) and tryFrom() (which returns null if the value does not exist).

print InvoiceStatus::tryFrom(3)->name;

If we decide we want to return something else than the name or the value of the enum, we can create a toString() method by adding it the the enum class:

public function toString(): string
{
return match($this) {
self::Pending => 'In asteptare',
self::Paid => 'Platita',
self::Void => 'Invalidata',
self:Failed => 'Esuata',
default => 'In asteptare'
}
}
print InvoiceStatus::tryFrom(3)->toString();

Inheritance, properties?

Enums can implement interfaces, use traits, but cannot extend classes. Enums does not accept properties to be defined, and this means that thes should not exist inside the traits used by the enums.

--

--