PHP and Enumerations

后端 未结 30 1485
有刺的猬
有刺的猬 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:22

    Pointed out solution works well. Clean and smooth.

    However, if you want strongly typed enumerations, you can use this:

    class TestEnum extends Enum
    {
        public static $TEST1;
        public static $TEST2;
    }
    TestEnum::init(); // Automatically initializes enum values
    

    With an Enum class looking like:

    class Enum
    {
        public static function parse($enum)
        {
            $class = get_called_class();
            $vars = get_class_vars($class);
            if (array_key_exists($enum, $vars)) {
                return $vars[$enum];
            }
            return null;
        }
    
        public static function init()
        {
            $className = get_called_class();
            $consts = get_class_vars($className);
            foreach ($consts as $constant => $value) {
                if (is_null($className::$$constant)) {
                    $constantValue = $constant;
                    $constantValueName = $className . '::' . $constant . '_VALUE';
                    if (defined($constantValueName)) {
                        $constantValue = constant($constantValueName);
                    }
                    $className::$$constant = new $className($constantValue);
                }
            }
        }
    
        public function __construct($value)
        {
            $this->value = $value;
        }
    }
    

    This way, enum values are strongly typed and

    TestEnum::$TEST1 === TestEnum::parse('TEST1') // true statement

提交回复
热议问题