PHP OOP Traits

PHP OOP Traits

A class in PHP can only have single inheritance. Traits are there to solve the problem.

About Traits

  • Used to declare methods that can be used in multiple classes.
  • Reduces code duplication.
  • Cannot be instantiated (create objects from).
  • Can have methods and abstract methods.
  • Methods can be in any visibility.

Declaring Traits

In PHP, traits are declared using the Trait keyword.

Trait MyTrait { ... }

Using Traits in Classes

To use a trait in a class, the trait name should be written inside the classes with the use keyword.

class MyClass {
	use MyTrait;

Traits Example

Let’s create two traits and use them in a class to see how they are working.

Tip: Use comma-separated names of traits to use multiple of them in a class.

PHP Traits Example

Trait Hello {
	public function hello() {
		echo "Hello";
Trait World {
	public function world() {
		echo "World";
class MyClass {
	use Hello, World;
$obj = new MyClass();
$obj -> hello();
$obj -> world();

Here’s what happened:

  • First we declared two traits, Hello and World.
  • Then we created our class, MyClass
  • By using two traits in the class, all the methods in traits will be available in the class.
  • Therefore, it was possible to call $obj -> hello() and $obj -> world() methods.

If there was another classes that you need to use the hello() function in, you can simply use the Hello trait in those classes. This reduces code duplication as there’s no need to redeclare the same method again and again.

Also, you would notice that we used two traits in the above example. If you used inheritance for this, extending multiple classes is not possible.

The weirdest part for a beginner in OOP is that there are several ways to do the same thing. The talent is figuring out the best way. To gain that skill, you will need a good knowledge on these concepts, also some real-world experience.

If you consider the above example, you can use all of these to create it: inheritance, abstraction, interfaces, and traits. Interfaces would not be the choice as you will need to declare the method again and again. If inheritance and abstraction is used, you will need to either inherit two times or have the both methods in the same parent class. So, traits would be the best choice in this case.

In the same way, you will get into the problem what to use in a certain situation. You should answer using your knowledge and experience.

Leave a Reply

Your email address will not be published. Required fields are marked *