PHP and Enumerations

后端 未结 30 1536
有刺的猬
有刺的猬 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 14:17

    My attempt to create an enum with PHP...it's extremely limited since it doesn't support objects as the enum values but still somewhat useful...

    class ProtocolsEnum {
    
        const HTTP = '1';
        const HTTPS = '2';
        const FTP = '3';
    
        /**
         * Retrieve an enum value
         * @param string $name
         * @return string
         */
        public static function getValueByName($name) {
            return constant('self::'. $name);
        } 
    
        /**
         * Retrieve an enum key name
         * @param string $code
         * @return string
         */
        public static function getNameByValue($code) {
            foreach(get_class_constants() as $key => $val) {
                if($val == $code) {
                    return $key;
                }
            }
        }
    
        /**
         * Retrieve associate array of all constants (used for creating droplist options)
         * @return multitype:
         */
        public static function toArray() {      
            return array_flip(self::get_class_constants());
        }
    
        private static function get_class_constants()
        {
            $reflect = new ReflectionClass(__CLASS__);
            return $reflect->getConstants();
        }
    }
    

提交回复
热议问题