×

php · level 3 · unit 3 · lesson 2

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

An is a type with a fixed menu of values.

Traffic lights are red, amber or green, never purple. A string cannot promise that, because "gren" is a string too. An enum lists every possible value as an , and nothing else ever exists. Light::Green is real. A typo is an error.

Use the enum as a type and a function can only receive one of its cases. Compare cases with ===, and get them all, in order, with Light::cases(). Each case also knows its own name through ->name.

<?php
enum Light {
    case Red;
    case Amber;
    case Green;
}
function canGo(Light $light): bool {
    return $light === Light::Green;
}
foreach (Light::cases() as $light) {
    if (canGo($light)) {
        echo "$light->name: go\n";
    } else {
        echo "$light->name: wait\n";
    }
}

Each case exists only once, so === is the right way to compare two of them.