PHP OOP Traits
π§© PHP OOP β Traits
Traits allow you to reuse code across multiple classes.
They solve a major limitation in PHP:
PHP does NOT support multiple inheritance
(a class cannot extend more than one parent class)
Traits allow us to βmix inβ methods from multiple places.
π¦ 1οΈβ£ What is a Trait?
A trait is like a mini-class containing methods (and properties) that can be reused in multiple classes.
Syntax:
Use a trait in a class:
π© 2οΈβ£ Using Multiple Traits in One Class
π§ 3οΈβ£ Traits with Properties
Use inside a class:
π₯ 4οΈβ£ Traits with Same Method Names (Conflict Resolution)
If two traits have same method name β PHP throws conflict.
We solve it with insteadof and as.
Example:
π¨ 5οΈβ£ Trait + Class Inheritance Together
π« 6οΈβ£ Traits Inside Traits (Trait Composition)
πͺ 7οΈβ£ Traits Cannot Be Instantiated
You cannot do:
Traits are not classes, only reusable code blocks.
π¦ 8οΈβ£ Practical Use Case β Logging System
π§ Traits vs Interfaces vs Inheritance
| Feature | Trait | Interface | Inheritance |
|---|---|---|---|
| Method body | β Yes | β No (only declare) | β Yes |
| Properties | β Yes | β (constants only) | β Yes |
| Multiple | β Yes (multi-trait) | β Yes | β Only one parent |
| Purpose | Reuse code | Define rules | Create structure |
π― Summary
| Concept | Meaning |
|---|---|
| Trait | Reusable set of methods/properties |
| use | Include trait inside class |
| insteadof | Resolve trait method conflict |
| as | Alias trait method |

