PHP and Enumerations

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

    abstract class Enumeration
    {
        public static function enum() 
        {
            $reflect = new ReflectionClass( get_called_class() );
            return $reflect->getConstants();
        }
    }
    
    
    class Test extends Enumeration
    {
        const A = 'a';
        const B = 'b';    
    }
    
    
    foreach (Test::enum() as $key => $value) {
        echo "$key -> $value
    "; }

提交回复
热议问题