Traits provide a way to reuse code in multiple classes without the limitations of single inheritance. They help avoid code duplication and allow combining methods from different sources.
<?php trait Hello { public function sayHello() { return "Hello from trait!"; } } class Greet { use Hello; } $g = new Greet(); echo $g->sayHello(); ?>
The class Greet uses the trait Hello, so it inherits the sayHello method. Calling $g->sayHello() outputs the string defined in the trait.
<?php trait A { public function talk() { return "Trait A"; } } trait B { public function talk() { return "Trait B"; } } class Person { use A, B; } $p = new Person(); echo $p->talk(); ?>
When two traits have methods with the same name and are used in one class without conflict resolution, PHP throws a fatal error due to ambiguity.
<?php trait A { public function talk() { return "Trait A"; } } trait B { public function talk() { return "Trait B"; } } class Person { use A, B { B::talk insteadof A; } } $p = new Person(); echo $p->talk(); ?>
The syntax 'B::talk insteadof A;' tells PHP to use the talk method from trait B instead of trait A, resolving the conflict.
Traits allow sharing common methods like logging across different classes that do not share a parent class, improving code reuse and design.
