PHP and Enumerations

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

    Some good solutions on here!

    Here's my version.

    • It's strongly typed
    • It works with IDE auto-completion
    • Enums are defined by a code and a description, where the code can be an integer, a binary value, a short string, or basically anything else you want. The pattern could easily be extended to support orther properties.
    • It asupports value (==) and reference (===) comparisons and works in switch statements.

    I think the main disadvantage is that enum members do have to be separately declared and instantiated, due to the descriptions and PHP's inability to construct objects at static member declaration time. I guess a way round this might be to use reflection with parsed doc comments instead.

    The abstract enum looks like this:

    code = $code;
            $this->description = $description;
        }
    
        public function getCode()
        {
            return $this->code;
        }
    
        public function getDescription()
        {
            return $this->description;
        }
    }
    

    Here's an example concrete enum:

    Which can be used like this:

    getCode().' : '.EMyEnum::$MY_FIRST_VALUE->getDescription().PHP_EOL.PHP_EOL;
    
    var_dump(EMyEnum::getAllMembers());
    
    echo PHP_EOL.EMyEnum::getByCode(2)->getDescription().PHP_EOL;
    

    And produces this output:

    1 : My first value

    array(3) {  
      [1]=>  
      object(EMyEnum)#1 (2) {  
        ["code":"AbstractEnum":private]=>  
        int(1)  
        ["description":"AbstractEnum":private]=>  
        string(14) "My first value"  
      }  
      [2]=>  
      object(EMyEnum)#2 (2) {  
        ["code":"AbstractEnum":private]=>  
        int(2)  
        ["description":"AbstractEnum":private]=>  
        string(15) "My second value"  
      }  
      [3]=>  
      object(EMyEnum)#3 (2) {  
        ["code":"AbstractEnum":private]=>  
        int(3)  
        ["description":"AbstractEnum":private]=>  
        string(14) "My third value"  
      }  
    }
    

    My second value

提交回复
热议问题