PHP OOP Traits

PHP Tutorial

 PHP OOP Traits

PHP OOP Traits

In PHP OOP 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.


  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:


 


  Using Multiple Traits in One Class


 


  Traits with Properties


 


  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:


 


  Trait + Class Inheritance Together


 


 Traits Inside Traits (Trait Composition)


 


  Traits Cannot Be Instantiated

You cannot do:

$t = new MyTrait(); // ERROR

Traits are not classes, only reusable code blocks.


Practical Use Case – Logging System


 


 Traits vs Interfaces vs Inheritance

FeatureTraitInterfaceInheritance
Method body Yes No (only declare) Yes
Properties Yes (constants only) Yes
MultipleYes (multi-trait) Yes Only one parent
PurposeReuse codeDefine rulesCreate structure

 Summary

ConceptMeaning
TraitReusable set of methods/properties
useInclude trait inside class
insteadofResolve trait method conflict
asAlias trait method

You may also like...