What are Traits in PHP ?

October 4, 2017 By - Usama Muneer | 490

    What are Traits?

    Traits are simply the way to share methods among classes in your application while keeping an equal eye on DRYing up code and making sure its re-usability in the application.

    In this article, we’ll go through the problem and then look at how using Traits can solve it for us.

    User Classes

    Let’s assume, we want to create an admin panel along side the basic users functionality as well. So basically, we would have a couple of classes to start with.

    class User {
    
    }
    
    class Admin {
    
    }

    These classes might share a couple of methods but on the same side might not share all of them. To tackle this type of problem, we’ll create a Trait like so

    trait Authenticatable {
    
    //List of Methods
    
    }

    And to use methods from this Trait, we’ll simple use the use keyword,

    class User {
    
        use Authenticatable;
    
    }

    Well that’s it. Its this simple to DRY up your application’s code-base using traits.

    To understand the difference between the Interfaces and Traits in PHP, you can check the below link.

    Final Words

    Traits are important part of PHP application as PHP doesn’t support multiple inheritances. Traits comes to the rescue and lets you share methods between classes with ease.

    If you’ve any suggestions or feedback, do write us a comment below. You can also follow us on Twitter.

    blog user
    Usama Muneer

    A web enthusiastic, self-motivated & detail-oriented professional Full-Stack Web Developer from Karachi, Pakistan with experience in developing applications using JavaScript, WordPress & Laravel specifically. Loves to write on different web technologies with an equally useful skill to make some sense out of it.

    Related Posts

    Its always considered a good practice to keep your machine updated with the latest PHP version. In this short article, we'll look at the simple steps on upgrading our PHP to 7.2

    If you want your table to have literally one of anything, then one to one is the most simplest relationship. For instance, a token is generated for resetting a user password & its a simple one to one relationship between users and password_resets table.

    If you're using Laravel's default authentication for your user management system, but wanted to change URI's and text in the default Password Reset email. Well There's a way out we can achieve that in Laravel.

    As you might have heard, Laravel 5.6 is out with lots of new stuff packed for developers. Here's what you need to know before migrating your website from Laravel5.5 to Laravel 5.6