PHP Interface
##Using interface (interface), you can specify which methods a certain class must implement , but the specific content of these methods does not need to be defined.
The interface is defined through the interface keyword, just like defining a standard class, but all methods defined in it are empty.
All methods defined in the interface must be public. This is a characteristic of the interface. (Recommended learning: PHP programming from entry to proficiency)
Implementation (implements)
To implement an interface, use the implements operation symbol. The class must implement all methods defined in the interface, otherwise a fatal error will be reported. A class can implement multiple interfaces. Use commas to separate the names of multiple interfaces.Note:
When implementing multiple interfaces, methods in the interfaces cannot have the same name.Note:
Interfaces can also be inherited, by using the extends operator.Note:
To implement an interface, a class must use the method that is exactly the same as the method defined in the interface. Otherwise a fatal error will result.Interface instance
<?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; } } // 下面的写法是错误的,会报错,因为没有实现 getHtml(): // 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; } } ?>
The above is the detailed content of php what is interface. For more information, please follow other related articles on the PHP Chinese website!