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?