PHP and Enumerations

后端 未结 30 2131
有刺的猬
有刺的猬 2020-11-22 13:39

I know that PHP doesn\'t have native Enumerations. But I have become accustomed to them from the Java world. I would love to use enums as a way to give predefined values whi

30条回答
  •  醉话见心
    2020-11-22 13:59

    This is my take on "dynamic" enum... so that i can call it with variables, ex. from a form.

    look at updated verison below this codeblock...

    $value = "concert";
    $Enumvalue = EnumCategory::enum($value);
    //$EnumValue = 1
    
    class EnumCategory{
        const concert = 1;
        const festival = 2;
        const sport = 3;
        const nightlife = 4;
        const theatre = 5;
        const musical = 6;
        const cinema = 7;
        const charity = 8;
        const museum = 9;
        const other = 10;
    
        public function enum($string){
            return constant('EnumCategory::'.$string);
        }
    }
    

    UPDATE: Better way of doing it...

    class EnumCategory {
    
        static $concert = 1;
        static $festival = 2;
        static $sport = 3;
        static $nightlife = 4;
        static $theatre = 5;
        static $musical = 6;
        static $cinema = 7;
        static $charity = 8;
        static $museum = 9;
        static $other = 10;
    
    }
    

    Call with

    EnumCategory::${$category};
    

提交回复
热议问题