Here is a comparison between Interface, Abstract class, and Trait in PHP. Let’s take a look at that side-by-side comparison in a table-
Criteria / Rule | Interface | Abstract Class | Trait |
---|---|---|---|
Can be instantiated | ![]() | ![]() | ![]() |
Can contain public property | ![]() | ![]() | ![]() |
Can contain protected property | ![]() | ![]() | ![]() |
Can contain private property | ![]() | ![]() | ![]() |
Can contain public constant | ![]() | ![]() | ![]() |
Can contain protected constant | ![]() | ![]() | ![]() |
Can contain private constant | ![]() | ![]() | ![]() |
Can contain public abstract method(signature only) | ![]() | ![]() | ![]() |
Can contain protected abstract method(signature only) | ![]() | ![]() | ![]() |
Can contain private abstract method(signature only) | ![]() | ![]() | ![]() |
Can contain public method(normal) | ![]() | ![]() | ![]() |
Can contain protected method(normal) | ![]() | ![]() | ![]() |
Can contain private method(normal) | ![]() | ![]() | ![]() |
Can inherit from normal class | ![]() | ![]() | ![]() |
Can inherit from an abstract class | ![]() | ![]() | ![]() |
Can implement interface(s) | ![]() | ![]() | ![]() |
Can use trait(s) | ![]() | ![]() | ![]() |
Can be inherited/used multiple times from a single class/interface/trait | ![]() | ![]() | ![]() |
Now let’s discuss in detail, about the use cases and when should we choose one of these, in our PHP code.