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';
//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()
{
public function __toString()
{
//default return
return self::SPRING;
}
}
return self::SPRING;
}
}
//Test the enum... prints out Spring.
echo ( new Season() );
echo ( new Season() );
//And if I wanted to choose just Summer
echo Season::SUMMER;
echo Season::SUMMER;
Java:
public enum Season {
//define the values
SPRING, SUMMER, AUTUMN, WINTER;
//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";
}
}
}
@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 );
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