×

php · level 3 · unit 2 · 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

A is a bundle of methods any class can borrow.

Inheritance shares code down a family tree. Sometimes unrelated classes need the same tool. A parrot and a football fan have nothing in common, but both can shout. A trait is a bundle of methods you can drop into any class at all.

Write trait, a name and its methods. Then write use and the trait's name inside a class, and PHP copies those methods in as if you had typed them there. A class can use several traits, separated by commas.

<?php
trait Shouts {
    public function shout(string $text): string {
        return strtoupper($text) . "!";
    }
}
trait Whispers {
    public function whisper(string $text): string {
        return strtolower($text) . "...";
    }
}
class Parrot {
    use Shouts, Whispers;
}
$polly = new Parrot();
echo $polly->shout("hello") . " " . $polly->whisper("GOODNIGHT") . "\n";

A trait can never be built with new, because it is a bundle of code, not a blueprint.