Before we introduce the interface, we need to know why to use the interface, here to introduce you.
So why use an interface?
In computer languages, only a handful of object-oriented objects support multiple inheritance, and the PHP language we learn, like most languages, does not support multiple inheritance. To be blunt, a parent class can have more than one child class, but subclasses can have only a single parent class.
What is multiple inheritance?
Multiple inheritance is a subclass, inheriting two or more parent classes, or multiple inheritance, which is not allowed in PHP. If you want to implement multiple inheritance in PHP, then we need to use the interface. Interfaces can be seen as a way to resolve multiple inheritance, and PHP's object-oriented interface is similar to other object-oriented language interfaces.
An introduction to the syntax of an interface class:
The interface class is declared by the interface keyword, and the class can contain only the non-implemented methods and some member variables in the following format:
Interface Interfacename{function interfaceName1 () {}function interfaceName2 () {}}
Attention:
Do not use keywords other than public to modify the class members in the interface, and for methods, it is also possible not to write the keyword. This is determined by the properties of the interface class itself.
The syntax for subclasses is described:
Subclasses are implemented through the Inplements keyword, and if you want to implement multiple interfaces, you should separate each interface with commas. And all the non-implemented methods in the interface class need to be fully implemented in the subclass, or a fatal error will occur.
Subclass Definition Format:
Class subclass implements InterfaceName1, Interfacename2{function InterfaceName1 () {}function InterfaceName2 () {}}
About Interface class instances:
<?phpheader ("Content-type:text/html;charset=utf-8"); interface a{ //Create Interface function A ();} Interface B{function B ();} Class PHP implements A{function A () {echo ' php Chinese web ';}} Class Html implements A, b{function a () {echo ' topic.alibabacloud.com is a free site ';} Function B () {echo ' topic.alibabacloud.com URL is www.php.cn ';}} $php = new PHP (), $html = new html (); $php->a (); Echo ' <br/> '; $html->a (); $html->b ();
All the non-implemented methods in the interface class need to be fully implemented in the subclass, or a fatal error will occur. You can try the partial implementation of the class in the interface to see if there will be a fatal error.