The difference and choice of abstract classes and interfaces in PHP

1. The use of the interface is through the keyword implements. The use of abstract classes is through the keyword extends. Of course, interfaces can also be inherited through the keyword extends.

2. Member variables (including class static variables) cannot be declared in an interface, but class constants can be declared. Various types of member variables can be declared in an abstract class to implement data encapsulation. (The member variables in the JAVA interface must be declared as public static final type)

3. Interfaces do not have constructors, but abstract classes can have constructors.

4. The methods in the interface are of the public type by default, while the methods in the abstract class can be modified with private, protected, and public.

5. A class can implement multiple interfaces at the same time, but a class can only inherit from one abstract class.

 

An abstract class is an interface.

  • If you want to create a model that will be adopted by some closely related objects, you can use abstract classes. Use an interface if you want to create functionality that will be adopted by some unrelated object.
    • Use an interface if you must inherit behavior from multiple sources.
    • If you know that all classes will share a common implementation of behavior, use an abstract class and implement that behavior in it.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324450230&siteId=291194637