What is a PHP Trait

What is a PHP Trait

Written by Dev Dojo on Oct 25th, 2016 Views Report Post

If you are new to PHP or even if you are a veteran PHP programmer you may have heard about traits but don't quite know what they do or why they are needed...

Well, luckily they are much easier than you would think and it only takes 60 seconds to grasp the concept.

So, what are these so called traits?

Well, a trait is simply a class that contains methods. This trait can be shared with many classes. All classes that use this trait can make use of the trait methods.

Why might you want to use a trait?

There might be many reasons that you want to use a trait. One example might be that we have a function that needs to be used throughout our project. Well, we could always create a global function or we could include this function (method) inside of a trait. Then any place we need to use this method we can use this trait and that method will be available for us to use.

Take a look at the following trait:

trait Greeting{
	
	public function sayHello($name){
		return 'Hello ' . $name;
	}

}

Now we can use this trait in any class:

class Post{
	use Greeting;
}

class Page{
	use Greeting;
}

Since we are using this trait in both classes above we now have access to the sayHello method in both instances: 

$post = new Post;
echo $post->sayHello('Bob');

$page = new Page;
echo $page->sayHello('Frank');

So, if you ever find yourself feeling limited by the single inheritance in PHP, meaning that a class can only be inherited from one other class, you may want to use a trait.

Comments (0)