Skip to content
Stefano Azzolini edited this page Aug 2, 2016 · 1 revision

The Enum class allow you to easily create immutable enumerations.

Define an enumeration


class Days extends Enum {
  const MONDAY    = 1;
  const TUESDAY   = 2;
  const WEDNESDAY = 3;
  const THURSDAY  = 4;
  const FRIDAY    = 5;
  const SATURDAY  = 6;
  const SUNDAY    = 7;
}

Enumeration values can also be strings :

class AIStatus extends Enum {
  const IDLE        = 'idle';
  const PATROL      = 'ptrl';
  const SCOUTING    = 'scou';
  const DISTRACTED  = 'dist';
  const FOCUSED     = 'focs';
  const ATTACKING   = 'attk';
  const DEFENDING   = 'defn';
  const FLEEING     = 'flee';
  const RESTING     = 'rest';
  const UNCONSCIOUS = 'unks';
  const FRIENDLY    = 'frnd';
  const HOSTILE     = 'host';
}

Note: Enum class cannot be instantiated.

Accessing labels


var_dump(
  Days::FRIDAY,          // int(5)
  AIStatus::FRIENDLY     // string(4) "frnd"
);

Check if a value is valid


You can check if a value is a part of the Enumeration using the has static method.

var_dump(
  Days::has('Sunday'),       // bool(true)
  AIStatus::has('resting'),  // bool(true)
  AIStatus::has('foobar')    // bool(false)
);

Retrieve the label of a value


You can the corresponding label for a valid value of the Enumeration using the key static method.
If no match is found the method returns false

var_dump(
  Days::key(1),          // string(6) "MONDAY"
  Days::key(21),         // bool(false)
  AIStatus::key('ptrl')  // string(6) "PATROL"
);
Clone this wiki locally