Enumeration in PHP

February 20, 2009 · Filed Under PHP 

An enumeration is a set of constant values, each of which is given a descriptive name.
Each value in an enumeration corresponds to a preset integer. In your code, however, you can refer to an enumerated value by name, which allows you to create more readable code and also simplify your coding experience.

Enumerations provide an alternative to the #define preprocessor directive with the advantages that the values can be generated for you and obey normal scoping rules.

In C, C++ and C#, enum types can be used to set up collections of named integer constants. (The keyword enum is short for “enumerated”.)

The traditional C way of doing this was something like this:

#define SPRING   0
#define SUMMER   1
#define FALL     2
#define WINTER   3

An alternate approach using enum would be

enum { SPRING, SUMMER, FALL, WINTER };

The example above illustrate the enumeration declarations, the identifiers are given the values 0 through 3 by default.

The concept of enumerated values is extremely important, because it can be extensively used within your classes and libraries. Unfortunately there is no predefined function that handle this process in PHP. You need to create your own enumerations to overcome this limitation.

Here is quick and dirty workaround:

  1. <?php
  2. function enum() {
  3.    $argc = func_num_args(); // a count of the arguments supplied to the program
  4.    $argv = func_get_args(); // a string array of arguments.
  5.  
  6.    for($int = 0; $int < $argc; $int++)
  7.          define($argv[$int], $int);
  8. }
  9. // usage of enum()
  10. enum ("SPRING", "SUMMER", "FALL", "WINTER" );
  11. ?>

func_num_args — Returns the number of arguments passed to the function.
func_get_args — Returns an array comprising a function’s argument list.
define — Defines a named constant

[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

Comments

Comments are closed.