Skip to content

6. Enums and match

A task has a priority: low, normal or high. An enum is a type with a fixed list of values, so no other priority can exist:

<?nvs
// This program gives each task a priority from an enum, and prints a label for it.
class Task
{
enum Priority { Low, Normal, High }
public string $title;
public Priority $priority;
public function constructor(string $title, Priority $priority = Priority::Normal)
{
$this->title = $title;
$this->priority = $priority;
}
public function line(): string
{
// `match` returns the result of the arm that equals the priority.
string $label = match ($this->priority) {
Priority::High => 'high',
Priority::Normal => 'normal',
Priority::Low => 'low',
};
return $this->title . ' (' . $label . ')';
}
}
// Outside `Task`, the enum is `Task::Priority`.
echo (new Task('Pay rent', Task::Priority::High))->line(), "\n";
echo (new Task('Buy milk'))->line(), "\n";
echo (new Task('Sort photos', Task::Priority::Low))->line(), "\n";
Output
Pay rent (high)
Buy milk (normal)
Sort photos (low)

The enum is declared inside Task, because only Task uses it. Inside the class it is Priority, and outside it is Task::Priority. Task::Priority::High is one case of the enum. The constructor gives $priority the default Priority::Normal. The second task uses this default.

match compares the priority with each arm and returns the result of the arm that is equal. This match has an arm for every case, so it needs no default.

Read more in Syntax: enums and Syntax: match.

Next: step 7, JSON.