Skip to content
Chris Russell edited this page Aug 30, 2015 · 10 revisions

php-enum

This project is an Enumeration implementation for PHP >=5.5 which is based on the Java Enum data type.

Normally, I don't try to make force one language's constructs into a different language. However, in my time with Java I have grown to appreciate their Enum data type. I believe the functionality offered is significant enough to warrant a php implementation.

I feel it's important to note that, while the implementation of php-enum is of my own design, the patterns and concepts behind it are based heavily on the Java Enum data type. In my time with Java, I've found them to be very good at solving a specific problem. I can not take credit for the ideas behind many of the features that are built into this implementation. For more information on the Java data type, please look here: http://docs.oracle.com/javase/tutorial/java/javaOO/enum.html

What is an Enum?

Simply put, an Enum (short for Enumeration) is a finite collection of predefined values.

Within the context of this implementation, you can think of them as a collection of complex constants where each item in the collection is represented by an immutable instance of a specific class.

Why?

In software development a list of available values is often necessary. These are often represented as class constants such as this:

class ChatColors
{
  const LIGHT_RED = 1;
  const DARK_BROWN = 2;
  ...
}

Often, this is sufficient but there are some limitations of this approach.

In the example of ChatColors, the constants successfully provide a way to uniquely and uniformly identify that you want your chat text to appear as light red or dark brown. However, they don't give us any of the functional attributes of a chat color such as its HTML hex code or RGB values.

This is where php-enum comes into play; it provides a way to represent all of the immutable properties of the chat colors for use in an easy and familiar way... as a class instance.

$color = ChatColor::LIGHT_RED();
$color->getHexCode();  // #FF4C4C
$color->getRedValue(); // 255
$color->getGreenValue(); // 76
$color->getBlueValue(); // 76
Clone this wiki locally