# Usefullness of Enum Types
I'm starting to find myself resort to using Enum types more and more in my projects. Enum types are perfect to model a class around related finite values.
An order might have 3 statuses. We can put these three statuses into a class and have each one associated with a small integer to be persisted in the database.
- Pending
- Processing
- Completed
final class OrderStatus
{
const Pending = 0;
const Processing = 1;
const Completed = 2;
}
Declaring the class as final makes the class immutable giving us the confidence that the values will never change.
Marking an order as completed would be more readable compare to using a number. Another benefit is not having to refer back to the class to remember which value corresponds to specific status.
$order->setStatus(1);
$order->setStatus(Order::Completed);
Using the statuses in a form input such as a select would feel quite natural.
<select>
<option value="0">Pending</option>
<option value="1">Processing</option>
<option value="2">Completed</option>
</select>
The true power of Enums come out when using them to have a single variable represent multiple options. Commonly known as Enum flags and can be made possible because of bitwise operations.
Enum flags appear in game development often. A shield can have different resistant to certain elements such as earth, air, fire and water.
Lets use values of increments of 1 first. We will convert these numbers to their binary representation.
final class ElementType
{ // Binary
const None = 0; // 000000
const Earth = 1; // 000001
const Air = 2; // 000010
const Fire = 3; // 000011
const Water = 4; // 000100
}
Now lets look at the binary representation when values are powers of 2
final class ElementType
{ // Binary
const None = 0; // 000000
const Earth = 1; // 000001
const Air = 2; // 000010
const Fire = 4; // 000100
const Water = 8; // 001000
}
Looking closely at the binary representation it allows us to conveniently represent each element as a column in the sequence of bits.
001010 would represent water and air.
The below Bitwise operators will allow us to operate on our elements:
- Bitwise OR - Combining multiple elements.
- Bitwise AND | Bitwise NOT - Remove an element from the combination.
- Bitwise XOR - Allows toggling an element on and off.
TIP
In php you can use left shift operators 1 << (0,1,2...)
Most of the time you will be using enums to represent a single value which provides readability, immutability and prevents typos that may lead to bugs.