Back to results for “OOP & Classes”
PHP › Traits

Why would a developer choose to use a trait instead of simply duplicating the same method directly into multiple different classes?

Beginner

Answer

Duplicating the exact same method across several different classes means that if a bug is ever found or the behavior needs to change, that same fix or change has to be manually applied and kept in sync across every single one of those duplicated copies, which is error prone and easy to forget, whereas defining that shared logic once inside a trait and having every relevant class simply use that trait means there is only ever one single place that needs to be updated, and every class using that trait automatically benefits from that one change immediately.
trait Timestampable {
    public function getCreatedAgo(): string {
        return $this->createdAt->diff(new DateTime())->days . ' days ago';
    }
}
Real-world example A team notices that several unrelated model classes each contain their own separate, slightly inconsistent copy of the exact same timestamp formatting logic, and consolidates that logic into a single shared Timestampable trait used consistently by all of them.

Common follow-ups: What other common cross cutting concerns are good candidates for being extracted into a trait?;Is there a risk of overusing traits throughout a codebase?