PHP and Enumerations

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

    I like enums from java too and for this reason I write my enums in this way, I think this is the most similiar behawior like in Java enums, of course, if some want to use more methods from java should write it here, or in abstract class but core idea is embedded in code below

    
    class FruitsEnum {
    
        static $APPLE = null;
        static $ORANGE = null;
    
        private $value = null;
    
        public static $map;
    
        public function __construct($value) {
            $this->value = $value;
        }
    
        public static function init () {
            self::$APPLE  = new FruitsEnum("Apple");
            self::$ORANGE = new FruitsEnum("Orange");
            //static map to get object by name - example Enum::get("INIT") - returns Enum::$INIT object;
            self::$map = array (
                "Apple" => self::$APPLE,
                "Orange" => self::$ORANGE
            );
        }
    
        public static function get($element) {
            if($element == null)
                return null;
            return self::$map[$element];
        }
    
        public function getValue() {
            return $this->value;
        }
    
        public function equals(FruitsEnum $element) {
            return $element->getValue() == $this->getValue();
        }
    
        public function __toString () {
            return $this->value;
        }
    }
    FruitsEnum::init();
    
    var_dump(FruitsEnum::$APPLE->equals(FruitsEnum::$APPLE)); //true
    var_dump(FruitsEnum::$APPLE->equals(FruitsEnum::$ORANGE)); //false
    var_dump(FruitsEnum::$APPLE instanceof FruitsEnum); //true
    var_dump(FruitsEnum::get("Apple")->equals(FruitsEnum::$APPLE)); //true - enum from string
    var_dump(FruitsEnum::get("Apple")->equals(FruitsEnum::get("Orange"))); //false
    
    

提交回复
热议问题