Last updated on June 23, 2023
PHP doesn’t support multiple inheritances, to overcome this problem, in PHP version 5.4 trait was introduced to object-oriented programming.
Traits allow you to declare methods that can be used in multiple classes. It means if you declare a method in the trait, you can use it in multiple classes. When you use a trait in a class, all the methods become part of that class.
Traits are an excellent example of Code Reusability, it helps to reduce lengthy classes and method duplications which saves developers time and improves code maintainability.
Syntax
You can declare a trait with a trait keyword.
trait YourTraitName {
// methods ...
}
It is good when you follow the naming convention. For traits, I suggest you use Pascal Case. To use a trait in a class you need to use use
keyword. Look at the below example.
class YourClass {
use YourTraitName;
}
Triats Example in PHP
Let’s understand traits by example. We have school and college classes that need a method for their admission status. So let’s create a School class and Admission trait for it.
Trait Admission{
public function open()
{
return "Admissions are open.";
}
}
class School{
use Admission;
}
$school = new School();
echo $school->open();
In the above example, we have an Admission trait that contains an open() method which tells admissions are open, and a School class that simply uses the Admission trait.
Similarly, we also need to use the trait in the college class. Look at the code below.
class College{
use Admission;
}
$college = new College();
echo $college->open();
So with the above example, we learned that traits can be used in multiple classes as College and School classes are using the same trait.
Do you see It prevented code duplication? Because if there were no traits in PHP then we would have added the open() method in both classes.
Traits Advantages