Interfaces in OOP in PHP
As you already know, abstract classes represent a set of methods for their descendants. Some of these methods can be implemented in the class itself, and some methods can be declared abstract and require implementation in child classes.
Imagine a situation where your abstract class consists only of a set of abstract public methods, without adding methods with implementation.
In fact, your parent class describes an interface for its descendants, that is, a set of their public methods that are mandatory for implementation.
Why do we need this: to make fewer mistakes when programming - by describing all the necessary methods in the parent class, we can be sure that all descendants will indeed implement them.
When this helps: let's say we create our parent class and several descendants for it. If later, after some time, for example, a month later, we decide to create another descendant, we will surely forget the details of our code and might well forget to write the implementation of some method in the new descendant. However, PHP itself will not allow losing a method - and will simply throw an error.
The same applies to another programmer working on your project. Let's say you wrote the code for the parent class, and then your colleague decided to create another descendant. Your colleague also will not be able to lose a couple of methods.
However, there is a problem: in fact, we made our parent class in order to write abstract public methods in it, but we ourselves or our colleague have the opportunity to accidentally add a non-public method or a non-abstract one to this class.
Suppose we want to physically prohibit making any methods other than abstract public ones in the parent. In PHP, for this purpose, instead of abstract classes, you can use interfaces.
Interfaces are classes where all methods are public and have no implementation. The code for the methods must be implemented by the classes that are descendants of the interfaces.
Interfaces are declared in the same way as regular
classes, but using the keyword interface
instead of the word class
.
For inheriting from interfaces, a
slightly different terminology is used: it is said that
classes do not inherit from interfaces, but implement
them. Accordingly, instead of the word extends
,
the keyword
implements
should be used.
You cannot create an object of an interface. All methods
of an interface must be declared as public
and must not have an implementation. An interface
can only have methods, not properties.
You also cannot have an interface and a class with
the same name.