php · level 3 · unit 2 · lesson 4
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
Two buttons share one trait. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
<?php
trait Counts {
private int $clicks = 0;
public function click(): int {
$this->clicks++;
return $this->clicks;
}
}
class LikeButton { use Counts; }
class ShareButton { use Counts; }
$like = new LikeButton();
$share = new ShareButton();
$like->click();
$like->click();
echo $like->click() . " likes, " . $share->click() . " share\n";
your turn
Your turn. Give a recipe a web address.
Add the trait to the class in the first blank, then type a recipe title, like Apple Crumble Pie. The trait turns it into a tidy web address.
fix it
The robot cannot introduce itself. Fix it.
- The error says
Undefined property: Robot::$name. Which line asks for$this->name? - The trait's method is copied into
Robot, so$thisis the robot. But the robot stores its name in a property with a different name. - On line 10, rename
$modelto$name, then run it.
nailed it
you shared code sideways with traits. :D
- A trait is a bundle of methods any class can
use. - A class can use several traits, separated by commas.
- Trait methods work on the properties of the class using them.
new words in your collection
- trait
This lesson isn’t saved. A free account remembers every lesson you finish.