Using interfaces (interface), you can specify which methods a class must implement, but you do not need to define the specifics of these methods.
Interfaces are defined by the interface keyword, just like defining a standard class, but all of the methods defined in it are empty.
All methods defined in the interface must be public, which is the attribute of the interface.
Implementation (implements)
To implement an interface, use the implements operator. All methods defined in the interface must be implemented in the class, or a fatal error will be reported. A class can implement multiple interfaces, separating the names of multiple interfaces with commas.
Note:
When implementing multiple interfaces, the methods in the interface cannot have duplicate names.
Note:
Interfaces can also be inherited by using the extends operator.
Note:
Class to implement an interface, it must be in a way that is exactly the same as the method defined in the interface. Failure to do so can result in fatal errors.
Constant
Constants can also be defined in an interface. Interface constants and class constants are used exactly the same, but cannot be overridden by subclasses or sub-interfaces.
Example
Example #1 Interface Example
Interface itemplate{public function SetVariable ($name, $var); Public Function gethtml ($template);} Implement interface//the following notation is correct for class Template implements itemplate{ Private $vars = Array (); Public Function SetVariable ($name, $var) { $this->vars[$name] = $var; } Public Function gethtml ($template) { foreach ($this->vars as $name = = $value) { $template = str_ Replace (' {'. $name. '} ', $value, $template); } return $template; }} The following wording is wrong, will error, because did not implement gethtml () class Badtemplate implements itemplate{ Private $vars = Array (); Public Function SetVariable ($name, $var) { $this->vars[$name] = $var; }}
Example #2 Expandable Interface
Interface a{public function foo (); Interface B extends a{public function Baz (Baz $baz);} Correct syntax Class C implements b{public function foo () {} public function Baz (Baz $baz) {}}//Error class D implements B{
public function foo () {} public function Baz (foo $foo) {}}
Example #3 inherit multiple interfaces
Interface a{public function foo (); Interface b{public function bar (); Interface C extends a,b{public function Baz (); Class D implements c{public Function foo () {} public function bar () {} public function Baz () {}}
Example #4 Using Interface constants
Interface a{ Const B = 1;} Output interface constant echo a::b;//error syntax Class B implements a{ const B = 1;}
interfaces, along with type constraints, provide a good way to ensure that an object contains certain methods. See instanceof operators and type constraints.