Interface refers to the interface. Using the interface (interface), you can specify which methods a certain class must implement, but you do not need to define the specific content of these methods.
We can define an interface through interface, just like defining a standard class, but all the methods defined in it are empty.
All methods defined in the interface must be public, which is a characteristic of the interface.
Implementation
To implement an interface, you can use the implements operator. The class must implement all methods defined in the interface, otherwise a fatal error will be reported. If you want to implement multiple interfaces, you can use commas to separate the names of multiple interfaces.
Note:
1. When implementing multiple interfaces, methods in the interfaces cannot have the same name.
2. Interfaces can also be inherited by using the extends operator.
Constant
Constant can also be defined in the interface. Interface constants and class constants are used exactly the same. They are all fixed values and cannot be modified by subclasses or subinterfaces.
Interface code example
<?php // 声明一个'iTemplate'接口 interface iTemplate { public function setVariable($name, $var); public function getHtml($template); } // 实现接口 // 下面的写法是正确的 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; } } // 下面的写法是错误的,会报错: // Fatal error: Class BadTemplate contains 1 abstract methods // and must therefore be declared abstract (iTemplate::getHtml) class BadTemplate implements iTemplate { private $vars = array(); public function setVariable($name, $var) { $this->vars[$name] = $var; } } ?>
For more related tutorials, please visit php Chinese website.
The above is the detailed content of What does interface in php mean?. For more information, please follow other related articles on the PHP Chinese website!