PHP and Enumerations

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

    Well, for a simple java like enum in php, I use:

    class SomeTypeName {
        private static $enum = array(1 => "Read", 2 => "Write");
    
        public function toOrdinal($name) {
            return array_search($name, self::$enum);
        }
    
        public function toString($ordinal) {
            return self::$enum[$ordinal];
        }
    }
    

    And to call it:

    SomeTypeName::toOrdinal("Read");
    SomeTypeName::toString(1);
    

    But I'm a PHP beginner, struggling with the syntax so this might not be the best way. I experimented some with Class Constants, using Reflection to get the constant name from it's value, might be neater.

提交回复
热议问题