Enums in PHP5

Posted: September 22nd, 2008 | Author: | Filed under: PHP | Comments Off on Enums in PHP5

Enums are very usefull. Unfortunately php does not natively implement it as a type. Not to worry, there is an easy workaround. To implement a simple status enum having values for “ok”, “not-ok” and “uncertain”, try:

abstract class Status implements Enum {
	const UNCERTAIN = 0; // or any other value you wish
	const OK = 1;
	const NOT_OK = 2;

	public static function values(){
		return new ArrayIterator(array(Status::UNCERTAIN,
			 Status::OK,
			 Status::NOT_OK));
	}
}

The values of the enumeration are now immutable, which makes it preferable to implementing such a construct as an array. The enum interface provides the static values() function that allows the caller to iterate over the values that have been enumerated.

interface Enum {
	/**
	 * Return an array containing the enum values to iterate over
	 * @return Traversable Contains enum values
	 */
	public static function values();
}

And that’s it. To use it, call Status::OK and the right value is used throughout your application. To loop, simply call foreach (Status::values() as $enum_value){...}.

This approach works well when several classes use the same naming for (some of) their properties. When using enums in a database, using this pattern will ensure the correct values are used. Also this will allow easy modification of the values in your app when the values in the database need to be changed.


Comments are closed.