Michael Budd

Important Cookie Notice: I'm currently doing my final year project for my MsC .. I'm currently tracking user behaviour on this site, currently this is only tracking time spent on a page... no personal information is stored.

A look at traits in PHP

This tutorial gives a quick explanation and demonstration in to how to use PHP Traits, and why.

Firstly, it's important to note that you'll need a minimum of PHP 5.4 to use traits! So if you haven't already... upgrade!

So why do we want to use traits? Well, like any other language, PHP has had to consider how it deals with multiple inheritance. Traditionally PHP has used the same principles of Java, allowing you to extend one class per class, and unlimited implementation of interface classes. This can be a little annoying, however, and what sometimes happens is a big daisy chain of inheritance, which doesn't help abide to the principle of loose coupling and high cohesion. PHP have now brought in traits, which allow us to implement the methods of other classes (in this case traits) without having to use inheritance. We can do this by simply using the "use" statement. We apply a "use" statement for each trait that we wish to include.

In my example, I simply require the traits and class files. You might want to do something a little nicer, however, like using the SPL autoloader, but for this demo I'll leave it as it is.

In my example, I create a class called TestClass and I want it to use the methods that exist inside of TestTrait and AnotherTrait. I have a method inside of TestClass with a method isEddWorking(). This method lets us know if Edd is working. Edd is a purely fictional character and in no way to be associated with the co-presenter of 3 Devs and a Maybe podcast. This method concatenates 2 strings that are return from a method in the TestTrait trait and a method from the AnotherTrait trait.

Then in my main index file, I simply instantiate the TestClass and echo out the returned value from the isEddWorking() method.

That's it. You can find the code within my bitbucket page, or see below.

As usual, thanks for reading!

/******* index.php **********/


$object = new TestClass();
echo $object->isEddWorking();


/******* testClass.php *******/

class TestClass {
	use TestTrait;
	use AnotherTrait;

	public function __construct() {


	public function isEddWorking() {

		return "Edd is " . $this->whatIsEddDoing() . 

			"\n" . $this->why();


/********* traits *************/

trait TestTrait {

	public function whatIsEddDoing() {

		return "browsing espn.com, not working.";

trait AnotherTrait {

	public function why() {

		return "Edd hates doing work.";


comments powered by Disqus