Somewhat surprisingly, PHP does not have native support for enumerations. With PHP 5.4, the native extension SPL_Types could be used to emulate this behavior with SplEnum
, but the last update to this extension was in 2012. On PHP 7, attempting to install the extension will throw compilation errors due to changed interfaces.
As such, I wanted to know what the currently recommended way of getting enum-like behavior is. I want to be able to write code at least similar to this:
enum DaysOfTheWeek
{
Monday = 1,
Tuesday = 2,
Wednesday = 3,
Thursday = 4,
Friday = 5,
Saturday = 6,
Sunday = 7
}
$day = DaysOfTheWeek::Monday;
echo $day; //Prints 1
My current code looks less concise and has lots of (unnecessary) overhead:
class DayOfTheWeek
{
private __value;
const Monday = 1;
const Tuesday = 2;
const Wednesday = 3;
const Thursday = 4;
const Friday = 5;
const Saturday = 6;
const Sunday = 7;
public function __construct(int $value)
{
if ($value !== DayOfTheWeek::Monday
&& $value !== DayOfTheWeek::Tuesday
&& $value !== DayOfTheWeek::Wednesday
&& $value !== DayOfTheWeek::Thursday
&& $value !== DayOfTheWeek::Friday
&& $value !== DayOfTheWeek::Saturday
&& $value !== DayOfTheWeek::Sunday
)
{
throw new InvalidArgumentException("Invalid day of the week");
}
}
public function GetValue(): int
{
return $this->__value;
}
}
Some clarifications:
Why not use an abstract class with a few constant values?
Because this completely defeats the idea of type hinting in PHP 7. The idea is that I can tell a function to accept an instance of this enumeration and be sure that it's a legitimate value.
Why don't you optimize the days of the week? You could make the check simpler by seeing if it's between 0 and 6.
Because enumerations don't have to be in order, or show any relation to each other. An enumeration could have the values 56, 1999, 120, -12400, 8, -1239 and 44. Code for an enumeration should not depend on the values of the enumeration.