Home  >  Article  >  Backend Development  >  Why does PHP need to write an interface?

Why does PHP need to write an interface?

(*-*)浩
(*-*)浩Original
2019-09-26 11:20:272421browse

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.

Why does PHP need to write an interface?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:How to deploy php projectNext article:How to deploy php project