Advertisement
Google Ad Slot: content-top
PHP OOP - Traits
PHP - What are Traits?
- A trait is a way to reuse methods across multiple classes without using inheritance.
- Unlike abstract classes, traits do not require class extension.
- PHP does not support multiple inheritance, but traits allow multiple classes to share functionality.
- Traits are declared with the
traitkeyword:
Syntax:
<?php
trait TraitName {
// some code...
}
?>
To use a trait in a class, you use the use keyword inside the class definition.
Syntax:
<?php
class MyClass {
use TraitName;
}
?>
Let's look at an example:
Explanation
- The
MessageTraittrait defines a methodshowMessage(). - The
MyClassuses theMessageTraitby using theusekeyword. - The
showMessage()method is available inMyClassand can be called on its object.
PHP - Using Multiple Traits
You can use multiple traits in a class by separating them with commas.
Let's look at another example:
Explanation
WalkandSpeakare two separate traits, each with its own method.Humanuses both traits viause Walk, Speak;.$person(instance ofHuman) can access bothwalk()andsayHello()methods—trait methods are treated as if they belong to the class.