The previous article introduced to you "What is the magic method in PHP? What are the commonly used magic methods? 》, this article continues to introduce to you what interfaces are in PHP? how to use?
It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.
Interface (abstract abstract class)
interface: interface
We first define an abstract class (abstr class), and then write two methods in it. If the subclass inherits the class we just defined, then the two classes we define must Implementation,
We use the definition of interface, (interface) For example, we write an interface at will, and then define a method,
<?php interface Pome { function poet(); } ?>
So how do we use the interface after we write it, and the interface The application is to write a class. Let the class we write implement the interface we just wrote. In other words, to make it implement the interface, we must implement the methods in the function, because the methods inside are abstract and we must implement them. If it is not implemented, an error will be reported. We can implement the interface through (implements).
<?php interface poet { function pome(); } class Person implements Poet { function pome() { echo '树叶落在木地板上' ; } } ?>
The code displays the result:
We implement the methods in the interface. Then we must implement the declaration in the interface.
implements: Implementation
The methods in the interface are all abstract methods, so abstract can be omitted.
Methods in the interface must be public
Only methods can be specified in the interface, and attributes cannot be written (constants can be written in the interface)
A class can implement multiple interfaces, separated by commas
For example There is also an interface. If I want to implement two interfaces at the same time, we need to add the interface behind the class class. We have implemented two interfaces, and then the two methods inside must be implemented by ourselves. If not The implementation will also report an error,
<?php interface poet { function pome(); } class Person implements Poet { function pome() { echo '树叶落在木地板上' ; } function like() { echo '我喜欢你'; } } ?>
A class can first inherit the parent class, and then implement the interface
The interface can inherit the interface, but the methods inside must be implemented
Recommended learning: php video tutorial
The above is the detailed content of What interfaces are there in PHP? how to use?. For more information, please follow other related articles on the PHP Chinese website!