2

According to the PHP manual

If a Pure Enum is serialized to JSON, an error will be thrown. If a Backed Enum is serialized to JSON, it will be represented by its value scalar only, in the appropriate type. The behavior of both may be overridden by implementing JsonSerializable

Let's try to implement JsonSerializable

enum Suit implements JsonSerializable
{
    case Hearts;
    case Diamonds;
    case Clubs;
    case Spades;
    
    public function jsonSerialize(): array {
        return [1, 2, 3, 4];
    }
}

echo json_encode(Suit::cases());

It prints:

[[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]]

Why [1,2,3,4] is duplicated 4 times?

How to control each case in an enum during serialization?

Rain
  • 3,416
  • 3
  • 24
  • 40

1 Answers1

5

In an enum every case is an object instance of that enum. That means JsonSerializable is implemented by each one of them. Suit::cases() will return a packed array of all cases in an enumeration (a.k.a objects) so jsonSerialize method will be called on each one of them hence the duplicated arrays.

How to control each case in an enum during serialization?

We can simply use a match expression

public function jsonSerialize(): string {
    return match($this) {
        Suit::Hearts => 'H',
        Suit::Diamonds => 'D',
        Suit::Clubs => 'C',
        Suit::Spades => 'S'
    };
}

It prints:

["H","D","C","S"]
Rain
  • 3,416
  • 3
  • 24
  • 40