ShareThis

Sunday, November 25, 2012

[PHP] Using Enums in PHP

PHP has no defined enums in its language, but there are easy ways of creating your own that are elegant, working solutions.

An enum can be mimicked using a class with constant values set to integers. Note: There are many ways of doing this. This is just one! At the bottom of the post is a link containing alternative solutions.


Code:
<?php

abstract class DaysOfWeek
{
    const Sunday = 0;
    const Monday = 1;
    // etc.
}

var $today = DaysOfWeek::Sunday;
?>

In this example the enum DaysOfWeek contains the constants Sunday and Monday. You could extend the code to use a switch case block in which the cases are stated like the $today variable:


Code:
<?php

abstract class DaysOfWeek
{
    const Sunday = 0;
    const Monday = 1;
    // etc.
}

var $today = DaysOfWeek::Sunday;

switch($today)
{
  case DaysOfWeek::Sunday:
  // do sunday logic
  break; 

  case DaysOfWeek::Monday:
  // Monday logic
  break;
}
?>

This is just one way of mimicking enums in PHP. Here are some other ways!

1 comments:

Nifty. Helped me set up a deck of cards enum

Post a Comment