DEV Community

Discussion on: My opinion on the PHP 8.1 Enum RFC

Collapse
 
nicolus profile image
Nicolas Bailly • Edited

Yeah I agree with you. I had not read the whole RFC, just the first few points and thought it was great (kinda like class constants on steroids). After reading your post I went back to the RFC and read the whole thing... And either this tries to cover some very limited use cases, or I don't understand the point of Enums.

Collapse
 
rvxlab profile image
RVxLab

Enums are particularly useful when you need to enforce a subset of items that are valid.

Let’s say you have a button that can have 4 different colours. You could make those colours an enum. Or it can have 1 of 3 sizes, that could be an enum.

Or as in the RFC, a suit can be an enum.

Now you can also solve this by just using a string, but what do you do when someone puts in an invalid value? You’d need to check for that. If you use an enum that check already happens during typechecking.

Collapse
 
nicolus profile image
Nicolas Bailly • Edited

Yes I think get that part, that's what I called 'class constants on steroids'. What I would do in PHP 7 is something like :

class Card
{
    const DIAMONDS = 'diamonds';
    const HEARTS   = 'hearts';
    const SPADES   = 'spades';
    const CLUBS    = 'clubs';

    const SUITS = [
        self::DIAMONDS,
        self::HEARTS,
        self::SPADES,
        self::CLUBS,
    ];


    public function __construct($suit)
    {
        if (!in_array($suit, self::SUITS)) {
            throw new InvalidArgumentException('invalid suit');
        }
    }
}

//works
$card = new Card(Card::SPADES);

//works :
$card = new Card('spades');

//throws an exception :
$card = new Card('hammers');
Enter fullscreen mode Exit fullscreen mode

With Enums it becomes a lot easier as you said.

But I don't need to put methods on my enums for that ! If I want a method that returns the shape or color of a suit I'll just create a Suit interface with a abstracts shape() and color() method and implement that method in a Spade class.
In the RFC they have an example where the color method uses a match statement to return the color and always return 'rectangle' as a shape. To me this kind of defeats the purpose of OOP.