Interfaces – a certain abstract template, which in the future should follow the class that uses this interface. You can create methods in the interface, but they must have no implementation. The interface ensures that the class will have some functionality that is described in the interface.
Use a keyword interface to create the interface
interface iProfile { }
! Usually the interface name starts with a lowercase “i“, but you can name the interface whatever you want.
Inside the interface you need to create methods that do not have implementation (function names and a list of parameters in parentheses followed by a semicolon).
interface iMessenger { function createprofile($name); }
! All methods created in the interface must be public
Implementation of the class interface
A class implements an interface using the “implements” keyword, followed by the name of the interface to use:
interface iProfile { function createprofile($name); } class Moderator implements iProfile { function createprofile($name); { echo "profile created!"; } }
! If a class implements an interface, then it must implement all the methods of that interface.
Inheriting an interface from another interface
//create interface interface iProfile { function createprofile($name); } //implement the interface with another interface interface iAdmin extends iProfile { }
Example of interface implementation:
//create interface interface iMessenger { function send($message); } //a function that will send a message, which takes the messenger object as the first parameter and the text to be sent as the second parameter. //In the function itself, the first parameter is an object that necessarily implements the iMessenger interface, so we can call the send() method on it to send a message. function sendMessage(iMessenger $messenger, $text) { $messenger->send($text); } //create a class that inherits the Messenger interface class EmailMessenger implements iMessenger { function send($message) { echo "Sending a message to email: $message"; } } $outlook = new EmailMessenger(); sendMessage($outlook, "Hello World"); ?>
The class can use many interfaces
//interfaces are listed in commas class Mobile implements iCamera, iMessenger { function makeVideo(){ echo "Video Record";} function makePhoto(){ echo "Make photo";} }