PHP Traits Explanation with Example

PHP Traits

PHP Traits

PHP 5.4 introduces the concept of traits. In PHP 5.4 version several new features was introduced, one such feature was PHP traits.

PHP traits help us to minimize code duplication in our codebase. Until the concept of traits, PHP uses classical inheritance model in which one class can inherit only one class. But sometimes, it is beneficial to inherit from multiple classes to avoid code duplication. To solve this problem, PHP community introduces the concept of traits.

PHP Traits

Trait allows us to reuse sets of methods freely in several independent classes living in different class hierarchies. In simple words, it gives you the flexibility to “copy and paste” code between classes. A trait cannot instantiate on its own like an abstract class.

 

 

How PHP Traits Work

In the above example, I have created one trait create and used in a class some. When I created an object of some class, it can use the method initiate despite it is not being defined in some class.

PHP built-in web server 

Multiple Traits

We can use multiple traits in our class by listing them in use statement separated with a comma.

 

NOTE – If two Traits insert a method with the same name, a fatal error is produced. If the conflict is not explicitly resolved.

Both traits (Create and Complete) has same method message. It will throw a fatal error if the conflict is not explicitly resolved.

To resolve this fatal error, we need to choose one of the conflicting methods using the insteadof operator.

Traits Vs Interface – Difference between Traits and Interfaces

An interface is a contract that says “this object is able to do this thing”, whereas a Trait is giving the object the ability to do the thing.

i) Using traits we can implement a method body while in an interface we can not provide a default implementation of a method body.

ii) We can implement multiple interfaces as well use traits in a class.

iii) An interface is used for Polymorphism(It means classes have different functionality while sharing a common interface), while we cannot use trait for Polymorphism.

Abstract class in PHP

Conclusion

PHP Traits allows code reusability across multiple classes and it’s a great way to add functionality to your classes horizontally. To know more about traits and their implementation you can refer PHP Manual.

Tagged , , , . Bookmark the permalink.

About WebRewrite

I am technology lover who loves to keep updated with latest technology. My interest field is Web Development.