Language:

Search

Difference between Interfaces and Traits in PHP

  • Share this:
Difference between Interfaces and Traits in PHP

If you're not familiar with the concepts of Traits and Interfaces in PHP, you can check on them from the below links:

Well, assume we're having a User and Admin classes, which are required to use some methods with the same functionality. We'll look on how do we achieve this using both Interfaces and Traits.

Using Interfaces

interface AuthenticatableInterface {
   public function getPassword();
   public function setPassword($password);
}

class User implements AuthenticatableInterface {
   public function getPassword(  ) {
      // TODO: Implement getPassword() method.
   }
   public function setPassword( $password ) {
      // TODO: Implement setPassword() method.
   }
}
class Admin implements AuthenticatableInterface {
   public function getPassword(  ) {
      // TODO: Implement getPassword() method.
   }
   public function setPassword( $password ) {
      // TODO: Implement setPassword() method.
   }
}

Using Traits

trait Authenticatable {
   public function getPassword(  ) {
      // TODO: Implement getPassword() method.
   }
   public function setPassword( $password ) {
      // TODO: Implement setPassword() method.
   }
}

class Admin implements AuthenticatableInterface {
   use Authenticatable;
}

class User implements AuthenticatableInterface {
   use Authenticatable;
}

Final Words

Well you can clearly see, using Traits can seriously DRY up your code and let you re-use & share methods within classes. Interfaces on the other hands are usable if you are required to use all of the methods in your class.

The above example is inspired by Laravel code-base. If you're familiar with Laravel, you can see how Taylor Otwell uses the combinations of Interfaces and Traits to clean up the code.

DYI

For this article, we've a bit of a task for you to explore Laravel files and directories to see how its working out. This will surely help you to understand the concept of Interfaces and Traits.

If you've any suggestions or feedback, do write us in the comment section below. You can also follow us on Twitter.

Related Readings

Usama Muneer

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.