Home > Article > Backend Development > Why does PHP need to write an interface?
Interface (software class interface) refers to the reference type that defines the agreement. Other types implement interfaces to ensure that they support certain operations. An interface specifies the members that must be provided by a class or other interface that implements it. Similar to classes, interfaces can contain methods, properties, indexers, and events as members.
An interface is a "class-like structure" that is more abstract than an abstract class.
In the interface, there are actually only these two members: constants and abstract methods. Interface methods can only be abstract and do not require the abstract keyword.
The purpose of interface(Recommended learning: PHP programming from entry to proficiency)
Single inheritance is the phenomenon of multiple inheritance in the "real world" A compromise - the reason is to not make the code too complex, but sometimes multiple inheritance situations need to be described.
Interface technology is a "compensation" for the compromise of single inheritance - interfaces can achieve multiple inheritance. However, the inheritance of interfaces is no longer called "inheritance", but is called "implementation" "implements.
Example:
<?php interfacedemoInterface{ public function doIt();//声明方法 } class hello implements demoInterface{ public function doIt(){ echo "实现接口中的方法"; } } $demo=new hello(); $demo->doIt(); ?>
Extension of interface
1. One class can inherit from other classes (only single inheritance) , and implement other interfaces at the same time (multiple implementations are possible), the form is as follows:
class 类名 B extends 类名A implements 接口名I1,接口名I2,...{ }
2. Interfaces can also inherit each other, the form is as follows:
Inteface 接口1 extends 接口2 { }
3. Constants and abstractions in the interface Methods can only be public and do not need to be written. Abstract methods do not need to use the abstract keyword.
The above is the detailed content of Why does PHP need to write an interface?. For more information, please follow other related articles on the PHP Chinese website!