Jump to content

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

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.