PHP only supports single inheritance, meaning a child class can inherit from just one parent class.
So, what if a class needs to inherit multiple behaviors? OOP traits address this issue.
Traits allow methods to be declared that can be used in multiple classes. Traits can contain both methods and abstract methods, and these methods can have any access modifier (public, private, or protected).
Traits are declared using the trait keyword:
<?php trait TraitName { // some code… } ?> |
To include a trait in a class, use the use
keyword:
<?php class MyClass { use TraitName; } ?> |
Here’s an example:
<?php trait message1 { public function msg1() { echo “OOP is fun! “; } } class Welcome { use message1; } $obj = new Welcome(); $obj->msg1(); ?> |
In this example, we declare a trait called message1
. We then create a class named Welcome
that uses this trait, making all its methods available within the class.
If other classes need to use the msg1()
function, they can simply include the message1
trait. This avoids code duplication, as there’s no need to redeclare the same method multiple times.
Here’s another example:
<?php trait message1 { public function msg1() { echo “OOP is fun! “; } } trait message2 { public function msg2() { echo “OOP reduces code duplication!”; } } class Welcome { use message1; } class Welcome2 { use message1, message2; } $obj = new Welcome(); $obj->msg1(); echo “<br>”; $obj2 = new Welcome2(); $obj2->msg1(); $obj2->msg2(); ?> |
In this example, we declare two traits: message1 and message2. We then create two classes: Welcome and Welcome2. The Welcome class uses the message1 trait, while the Welcome2 class uses both message1 and message2 traits (with multiple traits separated by commas).