Before introducing the interface, we need to know why we need to use the interface. Here we will introduce it to you.
So why use interfaces?
Among computer languages, only a few object-oriented ones support multiple inheritance. The PHP language we are learning, like most languages, does not support multiple inheritance. To put it bluntly, a parent class can have multiple subclasses, but a subclass can only have one parent class.
What is multiple inheritance?
Multiple inheritance is a subclass that inherits two or more parent classes. This is multiple inheritance, which is not allowed in PHP. If we want to implement multiple inheritance in PHP, then we have to use interfaces. Interfaces can be seen as a solution to multiple inheritance. PHP's object-oriented interface is similar to other object-oriented language interfaces.
Syntax introduction to interface classes:
Interface classes are declared through the interface keyword, and the class can only contain unimplemented methods and some member variables, format As follows:
interface InterfaceName{ function interfaceName1(){ } function interfaceName2(){ } }
Note:
Do not use keywords other than public to modify class members in the interface. For methods, it is okay not to write keywords. This is determined by the properties of the interface class itself.
Syntax introduction of subclasses:
Subclasses implement interfaces through the implements keyword. If you want to implement multiple interfaces, then each interface should be Separate with commas. And all unimplemented methods in the interface class need to be implemented in the subclass, otherwise a fatal error will occur.
Subclass definition format:
class SubClass implements InterfaceName1, InterfaceName2{ function InterfaceName1(){ } function InterfaceName2(){ } }
About interface class instances:
<?php header("content-type:text/html;charset=utf-8"); interface A{ //创建接口 function a(); } interface B{ function b(); } class Php implements A{ function a() { echo 'php中文网'; } } class Html implements A , B{ function a() { echo 'PHP中文网是免费网站'; } function b() { echo 'PHP中文网网址是www.php.cn'; } } $php = new Php(); $html = new html(); $php ->a(); echo '<br/>'; $html ->a(); $html ->b();
All unimplemented methods in the interface class need to be included in the subclass Implemented, otherwise a fatal error will occur. You can try to implement some of the classes in the interface yourself to see if any fatal errors will occur.
The above is the detailed content of PHP object-oriented multiple inheritance and interface usage. For more information, please follow other related articles on the PHP Chinese website!