The enumerated type for PHP


Enum

Whenever a procedure accepts a limited set of variables one could use an enumeration. Enumerations make for clearer and more readable code, particularly when meaningful names are used. A page at MSDN states the benefits of using an enumeration include:

  • reduction of errors caused by transposing or mistyping numbers,
  • simplify changing values in the future,
  • code is easier to read, which means it is less likely that errors will creep into it and/or
  • ensuring forward compatibility. With enumerations, your code is less likely to fail if in the future someone changes the values corresponding to the member names.

Enumerations are a must if your software solution spans across multiple projects and/or if the team you work is rather large. Enumerations are well known in the programming world, except for PHP. This is true while the database used most often with PHP, MySQL, does support Enums. This is why I took the liberty to write an implementation for enums in PHP.

The PHP Enum implementation can be downloaded from the page where I also listed some examples which can be used as kind of documentation. Click the link to go to the PHP Enum examples and/or documentation.

Implementing an enum with the abstract Enum base class is really simple. Let’s implement a Gender data type:

<?php
class Gender extends Enum {
   const Unknown = 0;
   const Male = 1;
   const Female = 2;
}

To use this in your code you can now use the gender like this:

$gender = Gender::Male();

And to use the enum you can do stuff like this:

echo $gender; // string value, echoes Male
 
echo $gender(); // const value (in this case an integer), echoes 1
 
echo $gender == Gender::Male()? 'true': 'false'; // echoes true
echo $gender == Gender::Female()? 'true': 'false'; // echoes false

The PHP Enum implementation can be downloaded from the page where I also listed some examples which can be used as kind of documentation. Click the link to go to the PHP Enum examples and/or documentation.

VN:F [1.3.1_645]
Rating: 10.0/10 (2 votes cast)
  • Share/Save/Bookmark
  1. No comments yet.
(will not be published)