I've been trying to study up on PHP lately, and I find myself getting hung up on traits. I understand the concept of horizontal code reuse and not wanting to necessarily inherit from an abstract class. What I don't understand is what is the crucial difference between using traits versus interfaces?
I've tried searching for a decent blog post or article explaining when to use one or the other, but the examples I've found so far seem so similar as to be identical.
Could anyone out there share their opinion/view on this?
I think
traits
are useful to create classes that contain methods which can be used as methods of several different classes.For example:
You can have and use this "error" method in any class that uses this trait.
While with
interfaces
you can only declare the method signature, but not its functions' code. Also, to use an interface you need to follow a hierarchy, usingimplements
. This is not the case with traits.It is completely different!
An interface defines a set of methods that the implementing class must implement.
When a trait is
use
'd the implementations of the methods come along too--which doesn't happen in anInterface
.That is the biggest difference.
From the Horizontal Reuse for PHP RFC:
Traits are simply for code reuse.
Interface just provides the signature of the functions that is to be defined in the class where it can be used depending on the programmer's discretion. Thus giving us a prototype for a group of classes.
For reference- http://www.php.net/manual/en/language.oop5.traits.php
The trait is same as a class we can use for multiple inheritance purposes and also code reusability.
We can use trait inside the class and also we can use multiple traits in the same class with 'use keyword'.
The interface is using for code reusability same as a trait
the interface is extend multiple interfaces so we can solve the multiple inheritance problems but when we implement the interface then we should create all the methods inside the class. For more info click below link:
http://php.net/manual/en/language.oop5.traits.php http://php.net/manual/en/language.oop5.interfaces.php
For beginners above answer might be difficult, This is the easiest way to understand it:
Traits
so if you want to have
sayHello
function in other classes without re-creating the whole function you can use traits,Cool right!
Not only functions you can use anything in the trait(function,variables,const..). also you can use multiple traits:
use SayWorld,AnotherTraits;
Interface
so this is how interface different from traits: You have to re-create everything in the interface in implemented class. interface doesn't have implementation. and interface can only have functions and const, it cannot have variables.
I hope this helps!
An interface is a contract that says “this object is able to do this thing”, whereas a Trait is giving the object the ability to do the thing.
A Trait is essentially a way to “copy and paste” code between classes.
try reading this article