jplus2 Posted May 16, 2012 Share Posted May 16, 2012 Hello guys, My first time to post here I need some help on achieving the same effect of enumeration in php I guess php don't support enumeration natively All help is much appreciated Thank you in advance Quote Link to comment https://forums.phpfreaks.com/topic/262584-enumeration-in-php/ Share on other sites More sharing options...
The Letter E Posted May 16, 2012 Share Posted May 16, 2012 Hello guys, My first time to post here I need some help on achieving the same effect of enumeration in php I guess php don't support enumeration natively All help is much appreciated Thank you in advance Do you have a small example of what you are trying to achieve, or are you looking for a more general enumeration object that can be reused? example 1: enum object <?php class enum { const data1 = 0; const data2 = 1; const data3 = 2; //etc... } print enum::data2; //prints '1' ?> sample 2 array: <?php $dataset = array(); $dataset[] = 'Sunday'; $dataset[] = 'Monday'; $dataset[] = 'Tuesday'; $dataset[] = 'Wednesday'; $dataset[] = 'Thursday'; $dataset[] = 'Friday'; $dataset[] = 'Saturday'; $datasetenum = array(); foreach( $dataset as $key => $val ){ $datasetenum[$val] = $key; } print $datasetenum['Tuesday']; //prints '2' print $datasetenum['Friday']; //prints '5' ?> Quote Link to comment https://forums.phpfreaks.com/topic/262584-enumeration-in-php/#findComment-1345770 Share on other sites More sharing options...
DavidAM Posted May 16, 2012 Share Posted May 16, 2012 This $datasetenum = array(); foreach( $dataset as $key => $val ){ $datasetenum[$val] = $key; } can be written in one line with array_flip as: $datasetenum = array_flip($dataset); Quote Link to comment https://forums.phpfreaks.com/topic/262584-enumeration-in-php/#findComment-1345796 Share on other sites More sharing options...
The Letter E Posted May 16, 2012 Share Posted May 16, 2012 This $datasetenum = array(); foreach( $dataset as $key => $val ){ $datasetenum[$val] = $key; } can be written in one line with array_flip as: $datasetenum = array_flip($dataset); Sweet! I've never come across a situation where I needed to do that, but now I know I can save a couple lines. Thanks! Quote Link to comment https://forums.phpfreaks.com/topic/262584-enumeration-in-php/#findComment-1345803 Share on other sites More sharing options...
smoseley Posted May 16, 2012 Share Posted May 16, 2012 Simple answer is NO - PHP does NOT support Enumerations. I use type classes with consts as in the first reply: class MyType { const TYPE1 = "TYPE1"; const TYPE2 = "TYPE2"; const TYPE3 = "TYPE3"; const TYPE4 = "TYPE4"; private function __construct() { // Non-instantiable } } Quote Link to comment https://forums.phpfreaks.com/topic/262584-enumeration-in-php/#findComment-1345806 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.