PHP and Enumerations

后端 未结 30 2127
有刺的猬
有刺的猬 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 13:57

    Here is a github library for handling type-safe enumerations in php:

    This library handle classes generation, classes caching and it implements the Type Safe Enumeration design pattern, with several helper methods for dealing with enums, like retrieving an ordinal for enums sorting, or retrieving a binary value, for enums combinations.

    The generated code use a plain old php template file, which is also configurable, so you can provide your own template.

    It is full test covered with phpunit.

    php-enums on github (feel free to fork)

    Usage: (@see usage.php, or unit tests for more details)

    getName()\n";
    foreach (FruitsEnum::iterator() as $enum)
    {
      echo "  " . $enum->getName() . "\n";
    }
    
    echo "->getValue()\n";
    foreach (FruitsEnum::iterator() as $enum)
    {
      echo "  " . $enum->getValue() . "\n";
    }
    
    echo "->getOrdinal()\n";
    foreach (CachedFruitsEnum::iterator() as $enum)
    {
      echo "  " . $enum->getOrdinal() . "\n";
    }
    
    echo "->getBinary()\n";
    foreach (CachedFruitsEnum::iterator() as $enum)
    {
      echo "  " . $enum->getBinary() . "\n";
    }
    

    Output:

    FruitsEnum::APPLE() == FruitsEnum::APPLE(): bool(true)
    FruitsEnum::APPLE() == FruitsEnum::ORANGE(): bool(false)
    FruitsEnum::APPLE() instanceof Enum: bool(true)
    FruitsEnum::APPLE() instanceof FruitsEnum: bool(true)
    ->getName()
      APPLE
      ORANGE
      RASBERRY
      BANNANA
    ->getValue()
      apple
      orange
      rasberry
      bannana
    ->getValue() when values have been specified
      pig
      dog
      cat
      bird
    ->getOrdinal()
      1
      2
      3
      4
    ->getBinary()
      1
      2
      4
      8
    

提交回复
热议问题