Did you like reading about interfaces in the previous post? Interfaces are neat for sure but did you notice the shortcomings? I really hope you did. In a nutshell, interface tells you what to do, it does not care how you do it. Now we are taking it a step further. We are going to discuss a feature that looks like an interface but acts like a class.

I will soon start posting about how to test your code using phpunit. It is very simple but the main idea behind unit testing (phpunit) your code is that when you expect certain inputs, you expect a certain output. You test to make sure your code behaves the same every time. When you use an interface, you know which methods the class has, sure, but code within those methods may vary. That is not always a good thing.

Let’s consider a different case. Raise your hand if you have ever written a duplicated code at some point. I am kidding put your hands down. We’ve all done it. Would you be okay with doing a copy/paste of the same code across multiple classes? You really should not. At all… Traits comes to the rescue.

Basically, when you create a trait, you are modulating your code because now that chunk of code can be injected to some other class. You now have code re-use instead of code copy paste.

Let’s say you are building an app for your school project. You have students and staff. They both share lots of things such as they are both users. It is safe to assume that each of them has a name, last name, email address, and session info to list a few. Would it be good to write methods like getName() for every single class or just have those methods in a single location which can be re-used across multiple classes? I choose the latter and I hope you do to.

trait User
protected $name;
public function setName($name)
$this->name = $name;

public function getName
return $this->name;


Now let’s use that in a class.

class Student
use User;
// bunch class methods goes here

Now, when you instantiate the student class, you have access to setName() and getName() methods.

When you care about how your class does things in addition to what it does use a traits.

A trait file is literally a chunk of code that gets copied and pasted into your class for you by the PHP interpreter. You can try and see for yourself by writing a method in your class and using that method in your trait. Your code will be fine. Same goes for properties within the trait as well. I really meant it when I said the PHP interpreter does a copy the code in your trait and paste it into the class.

Posted in PHP