Lotus@ 2008-10-31 18:51 采纳率: 100%
浏览 737
已采纳

和 Enumerations

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 which IDEs' auto completion features could understand.

Constants do the trick, but there's the namespace collision problem and (or actually because) they're global. Arrays don't have the namespace problem, but they're too vague, they can be overwritten at runtime and IDEs rarely (never?) know how to autofill their keys.

Are there any solutions/workarounds you commonly use? Does anyone recall whether the PHP guys have had any thoughts or decisions around enums?

转载于:https://stackoverflow.com/questions/254514/php-and-enumerations

  • 写回答

30条回答 默认 最新

  • Memor.の 2008-10-31 18:59
    关注

    Depending upon use case, I would normally use something simple like the following:

    abstract class DaysOfWeek
    {
        const Sunday = 0;
        const Monday = 1;
        // etc.
    }
    
    $today = DaysOfWeek::Sunday;
    

    However, other use cases may require more validation of constants and values. Based on the comments below about reflection, and a few other notes, here's an expanded example which may better serve a much wider range of cases:

    abstract class BasicEnum {
        private static $constCacheArray = NULL;
    
        private static function getConstants() {
            if (self::$constCacheArray == NULL) {
                self::$constCacheArray = [];
            }
            $calledClass = get_called_class();
            if (!array_key_exists($calledClass, self::$constCacheArray)) {
                $reflect = new ReflectionClass($calledClass);
                self::$constCacheArray[$calledClass] = $reflect->getConstants();
            }
            return self::$constCacheArray[$calledClass];
        }
    
        public static function isValidName($name, $strict = false) {
            $constants = self::getConstants();
    
            if ($strict) {
                return array_key_exists($name, $constants);
            }
    
            $keys = array_map('strtolower', array_keys($constants));
            return in_array(strtolower($name), $keys);
        }
    
        public static function isValidValue($value, $strict = true) {
            $values = array_values(self::getConstants());
            return in_array($value, $values, $strict);
        }
    }
    

    By creating a simple enum class that extends BasicEnum, you now have the ability to use methods thusly for simple input validation:

    abstract class DaysOfWeek extends BasicEnum {
        const Sunday = 0;
        const Monday = 1;
        const Tuesday = 2;
        const Wednesday = 3;
        const Thursday = 4;
        const Friday = 5;
        const Saturday = 6;
    }
    
    DaysOfWeek::isValidName('Humpday');                  // false
    DaysOfWeek::isValidName('Monday');                   // true
    DaysOfWeek::isValidName('monday');                   // true
    DaysOfWeek::isValidName('monday', $strict = true);   // false
    DaysOfWeek::isValidName(0);                          // false
    
    DaysOfWeek::isValidValue(0);                         // true
    DaysOfWeek::isValidValue(5);                         // true
    DaysOfWeek::isValidValue(7);                         // false
    DaysOfWeek::isValidValue('Friday');                  // false
    

    As a side note, any time I use reflection at least once on a static/const class where the data won't change (such as in an enum), I cache the results of those reflection calls, since using fresh reflection objects each time will eventually have a noticeable performance impact (Stored in an assocciative array for multiple enums).

    Now that most people have finally upgraded to at least 5.3, and SplEnum is available, that is certainly a viable option as well--as long as you don't mind the traditionally unintuitive notion of having actual enum instantiations throughout your codebase. In the above example, BasicEnum and DaysOfWeek cannot be instantiated at all, nor should they be.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(29条)

报告相同问题?

悬赏问题

  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题