×

php · level 3 · unit 4 · lesson 4

  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

Check inputs at the door, and bad data never gets inside.

A sits at the very top of a function. If the input is wrong, it throws straight away and the rest of the function never runs. This is how you : one clear error now beats a mystery bug three files later.

Put guards in a constructor and you get a , a small immutable object that can only hold a valid value. Once an Email exists, it is valid, so every function that asks for an Email can skip checking it ever again.

<?php
class Email {
    public readonly string $address;

    public function __construct(string $address) {
        $address = strtolower(trim($address));
        if (filter_var($address, FILTER_VALIDATE_EMAIL) === false) {
            throw new InvalidArgumentException("Not an email: $address");
        }
        $this->address = $address;
    }
}
function welcome(Email $email): string {
    return "Welcome email sent to $email->address";
}
echo welcome(new Email("  Sam@Example.COM ")) . "\n";

The value object tidies its input too, so every Email is lowercase with no stray spaces.