Saturday, August 19, 2006

Enumerations in PHP

Sometimes you stumble over stuff on the net and really think to yourself. Wow! Why does not everybody talk about it yet? My Subject of the day is Enumerations in PHP via SPL_Types. Basically it brings Enumerations to PHP, ensuring that a variable may only contain specific values based on a value domain. This should be looking something like this.


class Weekday extends SplEnum
{
  const Sunnday = 0;
  const Monday = 1;
  const Tuesday = 2;
  const Wednesday = 3;
  const Thursday = 4;
  const Friday = 5;
  const Saturday = 6;
  const __default = Weekday::Sunday;
}

$e = new Weekday;

var_dump($e); // shows object of type SplEnum
var_dump((int)$e); // int(0)

$e++;

var_dump($e); // shows object of type SplEnum
var_dump((int)$e); // int(1)
var_dump($e + 3); // int(4)
I have found this example over at a mailing list transcript at BeebleX. While there is certainly a trace of this functionality in the CVS Repository at php.net you cannot yet get a precompiled version of the extension at PHP-Snaps :-(.

Personal note: While I love PHP for the fact that it's a dynamically typed language, I consider Enumerations a big help, to communicate and ensure consistency of parameter values on public interfaces.

0 comments: