This article is mainly based on code, and its main function is to understand PHP's object-oriented interface (interface) and memos through examples.
To define an interface, use the interface keyword instead of the class keyword;
Constants can be defined in an interface, but member properties and member methods cannot be defined. This is different from abstract classes (abstract classes can be defined)
The methods in the interface are all abstract methods, but they are not modified with the abstract keyword and have no entity content
interface usb{
function connect();//Link USB
function quit();//Exit USB
interface chapai{
const DIANYA = '220v';
function charu();//Insert
function bachu(); // Pull out
}
Take three different electronic devices as an example: different devices implement USB interfaces in different ways, and thus implement different actions
Digital camera: plug it into the computer to pop up the picture browser U-Shield: install the driver, open the browser Mobile phone: charge
class shouji implements usb,chapai{ //A class can implement multiple interfaces
function connetc(){
echo 'Charging mobile phone, display phone content';
}
function quit(){
echo "Stop charging the phone, exit";
}
function charu(){ //Method to implement the power strip interface
echo "Mobile phone passes ".self::DIANYA."Voltage charging, plug-in charging";
}
function bachu(){
echo "Power off the phone, unplug it and leave".self::DIANYA."Voltage plug strip";
}
}
class xiangji implements usb{
function connetc(){
echo "Camera plugged into USB, display pictures";
}
function quit(){
echo "Camera pulled out";
}
}
class pc{
function usbConnect($usb){ //Pass in different electronic devices, get the object of the device and then call the link method of this electronic device
$obj = new $usb();
$obj->connect();
}
function usbQuit($usb){ //Same as above, pass in different devices and call the exit method of the corresponding device
$obj = new $usb();
$obj->quit();
}
}
$apple = new pc();
$apple->usbConnetc('shouji'); //new a computer object, and when passed to the mobile phone, the method of connecting the mobile phone to USB will be called
The above computer category can be understood as:
When the phone is connected to the computer via USB, the phone's method will be called; when the camera is connected to the computer via USB, the camera's method will be called