Wikis & learning

Share a method with a trait

Two unrelated classes may need the same small behavior. A trait can supply a method to both classes without forcing either class into a common inheritance hierarchy.

Two unrelated classes may need the same small behavior. A trait can supply a method to both classes without forcing either class into a common inheritance hierarchy.

Walkthrough

The shared method accepts its input as an argument and carries no mutable state. That makes the behavior easy to test and keeps its requirements visible to the classes that use it.

PHP example

<?php
trait TidyLabel {
    public function tidy(string $label): string {
        return trim(preg_replace('/\s+/', ' ', $label));
    }
}
class Card { use TidyLabel; }
echo (new Card())->tidy('  Small   steps  ');

Expected output

Small steps

Change and check

Add a second class that uses the trait. Confirm that it produces the same result for the same label.