PHP Traits - OOPs
A trait in PHP is a mechanism for code reuse in single inheritance languages like PHP. Traits allow you to group methods in a reusable way.
Traits are similar to classes, but intended to group functionality in a fine-grained and consistent way. They cannot be instantiated.
Why Use Traits?
Traits allow you to:
- Reuse common code in multiple classes.
- Keep your class structure cleaner.
- Work around PHP's single inheritance limitation.
Trait PHP में code reuse के लिए use होता है। PHP में single inheritance होती है, लेकिन traits से हम multiple class की तरह methods को reuse कर सकते हैं।
Trait को instantiate नहीं किया जा सकता, यह सिर्फ method group करने के लिए होता है।
Example: Trait with Employee
trait EmployeeInfo {
public $name, $age, $salary;
public function setData($name, $age, $salary) {
$this->name = $name;
$this->age = $age;
$this->salary = $salary;
}
public function display() {
echo "Name: $this->name
";
echo "Age: $this->age
";
echo "Salary: $this->salary
";
}
}
class Engineer {
use EmployeeInfo;
}
$e = new Engineer();
$e->setData("Sunita", 30, 75000);
$e->display();
Output:
Name: Sunita
Age: 30
Salary: 75000
Age: 30
Salary: 75000