Home > Backend Development > PHP Problem > php what is interface

php what is interface

(*-*)浩
Release: 2023-02-24 11:44:01
Original
3563 people have browsed it

PHP Interface

php what is 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

// 声明一个&#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;
    }
}
// 下面的写法是错误的,会报错,因为没有实现 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;
    }
}
?>
Copy after login

The above is the detailed content of php what is interface. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
php
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template