Lesson content
Read, practise, then check your understanding
Traits inject methods/properties into classes without establishing an is-a relationship. They are useful for focused implementation fragments but can hide dependencies when overused.
Practical example
<?php
trait Timestamps { public function touch(): void { $this->updatedAt = new DateTimeImmutable(); } }
final class Article { use Timestamps; private DateTimeImmutable $updatedAt; }
Resolve collisions with insteadof and alias/change visibility with as. Trait methods can depend on abstract requirements. Prefer collaborators when behavior has state, configuration, or an independently testable lifecycle.
Knowledge check
Answer every question correctly to complete this chapter.
0 of 10 checks passed
Your progress is saved on this device.