Monday, 8 August 2011

Enums in PHP and Java

This is mainly for my personal reference. Enums are quite useful to use in projects and save typing and make sure Strings/Integers match, because it's not uncommon that, for example, you type "list" instead of the expected word "List" or misspell things and other such tirivial issues.

PHP:

<?php

//PHP has no native Enum type so you need to manipulate
//a normal class to work how you want it to
final class Season
{
    //class constants are inherantly public and static
    const SPRING = 'Spring';
    const SUMMER = 'Summer';
    const AUTUMN = 'Autumn';
    const WINTER = 'Winter';

    public function __toString()
    {
        //default return
        return self::SPRING;
    }
}

//Test the enum... prints out Spring.
echo ( new Season() );
//And if I wanted to choose just Summer
echo Season::SUMMER;


Java:

public enum Season {
    //define the values
    SPRING, SUMMER, AUTUMN, WINTER;
   
    //for extra useability have it return a string of the chosen enum when needed
    @Override
    public String toString(){
        switch(this){
            case SPRING: return "Spring";
            case SUMMER: return "Summer";
            case AUTUMN: return "Autumn";
            case WINTER: return "Winter";
            default: return "Spring";
        }
    }
}

//usage - prints out Summer
System.out.println( Season.SUMMER );

1 comment:

  1. simple and clear post man, Indeed Enum are more versatile than one can think of , see the below post 10 examples of enum in java to know what else can you do with enum in java. keep the good work going.

    ReplyDelete