Trait vs inheritance
Learn the difference between trait and inheritance and when to use each.
Trait vs inheritance: vertical or horizontal?
In PHP inheritance is vertical: a class derives from a single parent and forms an 'is-a' relationship. When you write Dog extends Animal, you say 'a Dog is an Animal'.
A trait is horizontal: instead of 'is-a', it says 'has this capability'. Unrelated classes can share the same trait. And a class can use many traits, while inheriting from only one class.
When a trait, when inheritance?
When to use which? If there's a real type hierarchy, choose inheritance: Cat extends Animal, Car extends Vehicle. The subclass is a specialized parent.
If a behavior is shared across classes without kinship, choose a trait: both Robot and Phone can use a Battery trait; there's no need to tie them to a common parent.
Exercise Horizontal reuse in two unrelated classes
Define a Timestamp trait: its public function created(): string method does return "created";. Then Article and Comment classes use the trait with use Timestamp; (neither extends a parent; they are unrelated). Create instances with $a = new Article() and $c = new Comment(); call echo $a->created() . "\n" and echo $c->created() . "\n".
Show example solution
string { ... } }. Then add class Article { use Timestamp; } and class Comment { use Timestamp; }. Create both instances and call created().
Example solution:
<?php
// Use the Timestamp trait in two unrelated classes
trait Timestamp {
public function created(): string {
return "created";
}
}
class Article {
use Timestamp;
}
class Comment {
use Timestamp;
}
$a = new Article();
$c = new Comment();
echo $a->created() . "\n";
echo $c->created() . "\n";
Test yourself
-
Which statement about traits and inheritance is true?
- A class can inherit multiple classes but use only one trait
- A class can use multiple traits but inherit only one class
- Traits and inheritance are exactly the same
- Using a trait makes extends unnecessary
Show answer
A class can use multiple traits but inherit only one class — Correct. PHP has single inheritance, but a class can use any number of traits; this gives horizontal reuse.
-
Include a trait in an unrelated class
trait Battery { public function charge(): string { return "charging"; } } class Robot { ____ Battery; } $r = new Robot(); echo $r->charge() . "\n";Show answer
trait Battery { public function charge(): string { return "charging"; } } class Robot { use Battery; } $r = new Robot(); echo $r->charge() . "\n"; -
Match the concept to its category
- Dog extends Animal
- inheritance (is-a)
- class + use Battery
- horizontal reuse
- single parent limit
- PHP inheritance rule
- multiple trait combine
- trait advantage