Traits in PHP

If you worked with abstract objects before, you are aware of the single inheritance limitation, traits fix this in a very elegant way to allow us to write re-usable code.

Creating traits

Traits are created using the trait keyword:

trait MyTrait {

    function my_function()
       echo 'My first trait';


Using traits

To add a trait to a class, use the use keyword within the class:

class MyClass {

    use MyTrait;


That’s it! now you have all the trait’s methods available, to use multiple traits you can declare them on the same line separating them with a comma:

class MyClass {
    use MyTrait, MySecondTrait;


Note: traits can’t be instantiated.


One thought on “Traits in PHP

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s