DEV Community

Discussion on: My opinion on the PHP 8.1 Enum RFC

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.