Home >Backend Development >PHP Problem >What does interface in php mean?

What does interface in php mean?

王林
王林Original
2020-04-25 10:28:204587browse

What does interface in php mean?

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
 
// 声明一个&#39;iTemplate&#39;接口
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(&#39;{&#39; . $name . &#39;}&#39;, $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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn