PHP and Enumerations

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

    I have taken to using the approach below as it gives me the ability to have type safety for function parameters, auto complete in NetBeans and good performance. The one thing I don't like too much is that you have to call [extended class name]::enumerate(); after defining the class.

    abstract class Enum {
    
        private $_value;
    
        protected function __construct($value) {
            $this->_value = $value;
        }
    
        public function __toString() {
            return (string) $this->_value;
        }
    
        public static function enumerate() {
            $class = get_called_class();
            $ref = new ReflectionClass($class);
            $statics = $ref->getStaticProperties();
            foreach ($statics as $name => $value) {
                $ref->setStaticPropertyValue($name, new $class($value));
            }
        }
    }
    
    class DaysOfWeek extends Enum {
        public static $MONDAY = 0;
        public static $SUNDAY = 1;
        // etc.
    }
    DaysOfWeek::enumerate();
    
    function isMonday(DaysOfWeek $d) {
        if ($d == DaysOfWeek::$MONDAY) {
            return true;
        } else {
            return false;
        }
    }
    
    $day = DaysOfWeek::$MONDAY;
    echo (isMonday($day) ? "bummer it's monday" : "Yay! it's not monday");
    

提交回复
热议问题