PHP Enum
Built-in support for enums will be added in PHP 8.1.
Let’s imagine we have a car class Car
and we would like to tell the exactly possible colors for it. How do you do it without enum
?
I think you use const
as me. And than try to use this consts cases everywhere in the code.
class Color {
public const RED = "red";
public const BLACK = "black";
public const WHITE = "white";
}
And than in the code we use
(new Car())->setColor(Color::RED);
But the problem that if someone in the team does not know about this const Color
and the project is large, there is a high probability he ll not use it.
Here php8.1
enum
comes.
class Color {
public const RED = "red";
public const BLACK = "black";
public const WHITE = "white";
}
Now we can define class in this way
class Car {
private Color $color;
function setColor(Color $color): self {
$this->color = $color;
return $this;
}
}
And we use
(new Car)->setColor(Color::RED);
Enum methods
Enums can define methods, just like classes. This is a very powerful feature, especially in combination with the match
operator:
enum Color
{
case RED;
case BLACK;
case WHITE;
public function getColor(): string
{
return match($this)
{
Color::RED => 'red',
Color::BLACK => 'black',
Color::WHITE => 'white',
};
}
}
Methods can be used like so:
$color = Color::RED;
$color->color(); // 'red'
Enum interfaces
Enums can implement interfaces, just like normal classes:
interface HasColor
{
public function getColor(): string;
}
enum Status implements HasColor
{
case RED;
case BLACK;
case WHITE;
public function getColor(): string { /* … */ }
}
Enum values type
We can tell the exactly expected types of values
Example with string
enum Color: string
{
case RED = 'red';
case BLACK = 'black';
case WHITE = 'white';
}
Another example with int
enum PAYMENT: int
{
case PENDING = 1;
case CAPTURED = 2;
case AUTHORISED = 3;
case DONE = 4;
case REFUNDED = 5;
}
Listing enum values
You can use the static Enum::cases()
method to get a list of all available cases within an enum:
Color::cases();
and even more
foreach (Color::cases as $each) {
// ...
}
Thank you for your attention.
Need professional help in web or mobile development?
Recommendation for planning or estimation of your project?
Feel free to contact me here.
P.S. I really appreciate your like or share 🙏.