PHP and Enumerations

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

    The top answer above is fantastic. However, if you extend it in two different ways, then whichever extension is done first results in a call to the functions will create the cache. This cache will then be used by all subsequent calls, no matter whichever extension the calls are initiated by ...

    To solve this, replace the variable and first function with:

    private static $constCacheArray = null;
    
    private static function getConstants() {
        if (self::$constCacheArray === null) self::$constCacheArray = array();
    
        $calledClass = get_called_class();
        if (!array_key_exists($calledClass, self::$constCacheArray)) {
            $reflect = new \ReflectionClass($calledClass);
            self::$constCacheArray[$calledClass] = $reflect->getConstants();
        }
    
        return self::$constCacheArray[$calledClass];
    }
    

提交回复
热议问题