๐ŸŽ“ A1Learner
๐Ÿ”
0 of 27 lessons completed

Enums

An enum is a type that holds a fixed set of named cases. Each case is a value of the enum type, and no other value belongs to it.

A case name prints

The Suit enum declares three cases. The name property of the Hearts case prints as text.

<?php
enum Suit {
  case Hearts;
  case Spades;
  case Clubs;
}
$suit = Suit::Hearts;
echo $suit->name . "\n";

A method labels each case

The label method picks a colour word for the current case. Hearts gives red and Spades gives black.

<?php
enum Suit {
  case Hearts;
  case Spades;
  case Clubs;
  public function label() {
    return match($this) {
      Suit::Hearts => "red",
      Suit::Spades => "black",
      Suit::Clubs => "black",
    };
  }
}
echo Suit::Hearts->label() . "\n";
echo Suit::Spades->label() . "\n";

The cases method lists every case

The count line proves the enum holds three cases. The loop then prints each case name in declaration order.

<?php
enum Suit {
  case Hearts;
  case Spades;
  case Clubs;
}
echo count(Suit::cases()) . "\n";
foreach (Suit::cases() as $case) {
  echo $case->name . "\n";
}

Example

<?php
enum Coin {
  case Penny;
  case Nickel;
  case Dime;
  public function worth() {
    return match($this) {
      Coin::Penny => 1,
      Coin::Nickel => 5,
      Coin::Dime => 10,
    };
  }
}
echo Coin::Penny->name . " is worth " . Coin::Penny->worth() . "\n";
echo Coin::Dime->name . " is worth " . Coin::Dime->worth() . "\n";

Key points

  • The word enum starts the declaration and names the new type.
  • Each case line names one allowed value of the type.
  • Every case carries a name property that holds its case name as text.
  • The cases method lists every case in declaration order.
  • An enum can hold methods, and a method can work from the current case.
  • A method can pick a result for each case with a match on the current case.

In this example, the Coin enum declares three cases and one worth method. The method picks a number for the current case. The print lines pair each case name with its worth, so the penny line shows 1 and the dime line shows 10.

Note

A pure enum case holds a name only, and it stores no extra value.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does the cases method of an enum give back?