The Enumerated Data Type

29 Jun
2012

In my first post, switch-ing gears, I wrote about the differences between the switch statements in Java and PHP. Part of the difference was that in Java, you can’t switch on String type variables, but only on integers and another data type called an Enum, or an enumerated data type, which do not exist in PHP.

Enums are a data structure that contain a fixed set of constant members (called enumerators). The value of the Enum variable must be one of the defined constants. For example:

    public enum WeekDay {
        SUNDAY,MONDAY,TUESDAY,WEDNESDAY,THURSDAY,FRIDAY,SATURDAY;
    }

    WeekDay firstDay = WeekDay.SUNDAY;

Using any value that is not defined in the WeekDay enum, for example, “WeekDay.asdf”, will result in an error message stating that “asdf cannot be resolved or is not a field”. This gives us type safety, but I’ll come back to that in a minute.

You can sort of simulate the same type of functionality in PHP using constants in a standard class:

    public class WeekDay {
        public static const SUNDAY = 1;
        public static const MONDAY = 2;
        public static const TUESDAY = 3;
        public static const WEDNESDAY = 4;
        public static const THURSDAY = 5;
        public static const FRIDAY = 6;
        public static const SATURDAY = 7;
    }

    $firstDay = WeekDay::SUNDAY;

This will give you basically the same functionality as the Java enum, but with no type checking or safety. For example, if we have a function in our Java code that is expecting a parameter that must be one of the fields we defined in the WeekDay enum, we can express it like this:

    public void checkWeekDay(WeekDay day) {
        // ... do something to check the WeekDay
    }
 
    WeekDay day = WeekDay.SUNDAY;
    checkWeekDay(day);

This function will not accept any value except one of those defined in our WeekDay enum. If we were to use an integer instead, the integrity of our software is compromised, because we can not guarantee that the value of the integer passed to the function will be one of the allowed values (presumably a number from 1 to 7). Example:

    public String checkWeekDay(Integer day) {
        switch(day) {
            case 1:
                return "Sunday";
                break;
            case 2:
                return "Monday";
                break;
            case 3:
                return "Tuesday";
                break;
            case 4:
                return "Wednesday";
                break;
            case 5:
                return "Thursday";
                break;
            case 6:
                return "Friday";
                break;
            case 7:
                return "Saturday";
                break;
            default:
                throw new Exception("Integer value outside of acceptable range 1-7");
                break;
        }
    }
 
    Integer day = 450;
    try {
        checkWeekDay(day);
    } catch (Exception e) {
        // do something ugly here
    }

Yuck! Right?? Using our WeekDay enum, the error would have been caught before the program even compiled!

Another difference between the PHP and the Java is that using the enum data type in Java gives us the ability to list off all of the available members of the enum. In PHP we could technically use a ReflectionClass to list the class constants, but the code is much more involved than the Java equivalent. Let’s compare…

The Java:

    for (WeekDay wd : WeekDay.values()) {
        // this should print the names of the days of the week
        System.out.printf("Value: %s",wd.toString()); 
    }

The PHP:

    $r = new ReflectionClass('WeekDay');
    $constants = $r->getConstants();
    var_dump ($constants);

    /* 
     * Outputs:
     * Array
     * (
     *    ['SUNDAY'] => 1
     *    ['MONDAY'] => 2
     *    ['TUESDAY'] => 3
     *    ['WEDNESDAY'] => 4
     *    ['THURSDAY'] => 5
     *    ['FRIDAY'] => 6
     *    ['SATURDAY'] => 7
     * )
     *
     **/

This seems like a good solution, but in reality, this is overkill since the solution requires the instantiation of the entire ReflectionClass rather than accessing the properties of the class directly. Unfortunately, if you want to list class constants in PHP, this is the only method available.

1 Response to The Enumerated Data Type

Avatar

aster1sk

June 29th, 2012 at 7:07 pm

<? strtotime($str); ?> //beat that, Java.

Comment Form

top