Jump to content

Enumeration in PHP


jplus2

Recommended Posts

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'
?>

Link to comment
https://forums.phpfreaks.com/topic/262584-enumeration-in-php/#findComment-1345770
Share on other sites

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!

Link to comment
https://forums.phpfreaks.com/topic/262584-enumeration-in-php/#findComment-1345803
Share on other sites

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

    }

}

Link to comment
https://forums.phpfreaks.com/topic/262584-enumeration-in-php/#findComment-1345806
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.