Abstract class:
It is used for inheritance and cannot be instantiated. It is used for standardization. Subclass must implement all abstract methods of the parent class.
Interface:
It can be understood as a stricter abstract class.
First, like an abstract class, you can set standards. Because an interface has its own characteristics, you must implement all the methods in the interface, so that the project manager can define a specification in the interface, functions to be implemented
Second, php is a single inheritance. A class can only have one parent class. To solve this problem, an interface occurs. A class can implement multiple interfaces.
For example, consider a class named Media, which is used to describe the common nature of various public materials, because Media does not represent real entities, but some similar generalized representations, so you don't want to instantiate it directly. To ensure that this situation does not occur, you can declare that this class is abstract. Then, this abstract class is inherited from various derived Media classes, which ensures direct consistency of subclass, because all methods defined in the abstract class must be implemented in the subclass.
Abstract keywords must be added before the definition of an abstract class declared as an abstract class, as follows:
Abstract class Class_Name
{
// Insert attribute definitions here
// Insert mothod definitions here
}
Abstract classes ensure consistency, because any derived class must implement all abstract methods inherited by this abstract class. If no abstract method defined in the abstract class is implemented, a fatal error occurs.
Using Abstract classes or interfaces
When should I use interfaces and when should I use abstract classes? This is confusing and creates a lot of debate. However, the following factors can help you make a decision:
• If you want to create a model that will be used by closely related objects, you can use abstract classes. If you want to create functions that will be used by irrelevant objects, use interfaces.
• If the behavior must be inherited from multiple sources, the interface is used. The PHP class can inherit multiple interfaces, but cannot expand multiple abstract classes.
• If you know that all classes share a public behavior implementation, use an abstract class and implement this behavior in it. Actions cannot be implemented in interfaces.