PHP和Enum麻烦

时间:2013-10-27 18:50:38

标签: php database enums enumeration enumerable

我到处寻找,似乎无法解决这个问题。我的问题是,我正在尝试使用'enum'作为我的数据库中的排名,但不断收到错误。我在下面的内容中我希望能够根据成员的等级显示在特定的div中。这是我到目前为止,我哪里错了?如果有人能够了解这是否正确或我需要做些什么才能使其发挥作用,我将非常感激。

PHP:

class Rank
{
  // If no value is given during object construction this value is used
  const __default = 1;
  // Our enum values
  const Registered       = 1;
  const Legend           = 2;
  const Inactive         = 3;
  const Greenhorn        = 4;
  const FullMember       = 5;
  const JuniorAdmin      = 6;
  const SeniorAdmin      = 7;
  const Leader           = 8;
  const Founder          = 9;
  const OriginalFounder  = 10;
}

$registered     = new Rank(Rank::REGISTERED);
$legend         = new Rank(Rank::LEGEND);
$inactive           = new Rank(Rank::INACTIVE);
$greenhorn          = new Rank(Rank::GREENHORN);
$fullmember     = new Rank(Rank::FULLMEMBER);
$junioradmin        = new Rank(Rank::JUNIORADMIN);
$senioradmin        = new Rank(Rank::SENIORADMIN);
$leader         = new Rank(Rank::LEADER);
$founder            = new Rank(Rank::FOUNDER);
$originalfounder    = new Rank(Rank::ORIGINALFOUNDER);
$fail              = 1;

function responsibilities(Rank $rank)
{
  if (Rank::REGISTERED == $rank) {
    echo "Post something about being a registered member.\n";
  } elseif (Rank::LEGEND == $rank) {
    echo "Post something about being Legend.\n";
  } elseif (Rank::INACTIVE == $rank) {
    echo "Post something about being Inactive./n";
  } elseif (Rank::GREENHORN == $rank) {
    echo "Post something about being a Greenhorn./n";
  } elseif (Rank::FULLMEMBER == $rank) {
    echo "Post something about being a Full Member./n";
  } elseif (Rank::JUNIORADMIN == $rank) {
    echo "Post something about being a Junior Admin./n";
  } elseif (Rank::SENIORADMIN == $rank) {
    echo "Post something about being a Senior Admin./n";
  } elseif (Rank::LEADER == $rank) {
    echo "Post something about being a Leader./n";
  } elseif (Rank::FOUNDER == $rank) {
    echo "Post something about being a Founder./n";
  } elseif (Rank::ORIGINALFOUNDER == $rank) {
    echo "Post something about being an Original Founder./n";
  }
}

responsibilities($registered);
responsibilities($legend);
responsibilities($inactive);
responsibilities($greenhorn);
responsibilities($fullmember);
responsibilities($junioradmin);
responsibilities($senioradmin);
responsibilities($leader);
responsibilities($founder);
responsibilities($originalfounder);

responsibilities($fail);

HTML:

<p><?php echo $rank ?></p>

1 个答案:

答案 0 :(得分:1)

看起来您正在尝试使用SplEnum类来创建枚举。为了得到这样的枚举,你需要你的枚举类来扩展SplEnum抽象类。

class Fruit extends SplEnum
{
    const __default = self::Apple; // default value; could also be __default = 0;
    // values
    const Apple = 0;
    const Orange = 1;
}

我还没有对它进行测试,但我相当确定枚举中的常量是区分大小写的。也就是说,如果您定义上面的枚举Fruit,则可以使用Fruit::Orange但不能使用Fruit::ORANGE。我认为通常的惯例是使用所有大写,因为它们是常量。