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 | No | No | No |
Can contain public property | No | Yes | Yes |
Can contain protected property | No | Yes | Yes |
Can contain private property | No | Yes | Yes |
Can contain public constant | Yes | Yes | Yes |
Can contain protected constant | No | Yes | Yes |
Can contain private constant | No | Yes | Yes |
Can contain public abstract method(signature only) | Yes | Yes | Yes |
Can contain protected abstract method(signature only) | No | Yes | Yes |
Can contain private abstract method(signature only) | No | No | Yes |
Can contain public method(normal) | No | Yes | Yes |
Can contain protected method(normal) | No | Yes | Yes |
Can contain private method(normal) | No | Yes | Yes |
Can inherit from normal class | No | Yes | No |
Can inherit from an abstract class | No | Yes | No |
Can implement interface(s) | Yes | Yes | No |
Can use trait(s) | No | Yes | Yes |
Can be inherited/used multiple times from a single class/interface/trait | Yes | No | Yes |
Now let’s discuss in detail, about the use cases and when should we choose one of these, in our PHP code.