Enums allow a developer to define a custom type that is limited to one of a discrete number of possible values. Using it as an array key was not that straightforward.
Trying to find any information about it was misleading and confusing and did not work at all. At first, PhpStorm marked it as an error, which was confusing, so I thought maybe it was a bug. If I tried to run it, it was throwing TypeError: Illegal array key type
. Fortunately, I did find a way to make it work.
Let's create a backed enum based on the examples I found on the Internet. It has one value, and let's use it inside the trait:
<?php
enum MyEnum: string {
case MY_VALUE = '0';
}
trait MyTrait {
public function map(): array {
return [
MyEnum::MY_VALUE => 'My Value',
];
}
}
This will throw a TypeError. Although it is a string enum, PHP seems not to accept it. To make it work, you need to use ->value
, something like this, which will work just fine:
trait MyTrait {
public function map(): array {
return [
MyEnum::MY_VALUE->value => 'My Value',
];
}
}