Skip to content

Chapter 21 of 38

Traits

Reuse implementation horizontally and resolve method conflicts explicitly.

30 minutes 10 quick checksBy Subha Prasad
Lesson 21 of 38Course navigation

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.

Which statement best describes trait?
Which PHP term matches this description: A horizontal code-reuse unit inserted into classes.
Which statement best describes use?
Which PHP term matches this description: The class-body construct importing trait members.
Which statement best describes insteadof?
Which PHP term matches this description: Conflict resolution selecting one trait method over another.
Which statement best describes as?
Which PHP term matches this description: Trait adaptation changing alias or visibility.
Which statement best describes trait composition?
Which PHP term matches this description: Building reusable implementation fragments without an is-a relationship.

0 of 10 checks passed

Your progress is saved on this device.