What is Trait?

October 18, 2018 by admin

As we know that, PHP supports Single Inheritance and multilevel Inheritance. Okay, but what about multiple Inheritance.

PHP doesn't supports Multiple Inheritance.This is the basic drawback in it.

So, what is the solution?

Well, to overcome this problem we can use interface.Then how traits is different from interface. So, lets see what is the difference between interface and Traits

interface Traits
All the methods defined in the interface must be implemented in the class which implements it It is nothing but a set on methods defined and implemented in the class
it supports polymorphism it doesn't supports polymorphism
It can not provide a default implementation of a method body it provides a default implementation

A typical example of an interface

interface SayHelloWorld {
	public function sayHello();
	public function byeWorld();
}
class Earth implements SayHelloWorld {
	public function sayHello(){
		// implementation
	}
	public function byeWorld(){
	// implementation
	}
}

So, here in above example we can see that interface SayHelloWorld only defined methods and their implementation is done in class Earth.

A typical example of an traits

trait SayHelloWorld {
	public function sayHello() {
		echo 'Hello World!';
	}
	public function byeWorld(){
		echo 'Bye World!';
	}
}

class MyHelloWorld extends Base {
	use SayHelloWorld;

	public myWorld {
		echo 'Hello My World';
	}
}

So, in above example we are including SayHelloWorld trait in MyHelloWorld class which indirectly means that we are including all the methods of MyHelloWorld traits in our MyHelloWorld class