Home > Backend Development > PHP Tutorial > How to make an interface in php

How to make an interface in php

(*-*)浩
Release: 2023-04-06 17:32:01
Original
17860 people have browsed it

In PHP, you can use the syntax "interface Action(){public function eat( $foods ); }" to define an interface. This statement means that the interface defines "public" access attribute methods.

How to make an interface in php

Define the common behaviors of different classes, and then implement different functions in different classes.

The specific syntax of the PHP interface:

The interface is a part that can be composed of multiple parts to form a new thing;

The interface itself is abstract, internal The declared method is also abstract; a class can implement multiple interfaces at once without adding abstract

. The syntax is implemented with implements, and then the functions of the interface are implemented;

Interfaces can also be inherited based on bases, using extends;

Interfaces are descriptions of a bunch of methods, and attributes (member variables) cannot be added;

Interfaces are used for assembly into classes, and methods can only be public;

Interfaces serve as a strict specification to reduce communication between developers and callers

Interface implementation

Example of humans and animals implementing a certain action

Definition of interface

interface Action(){ 
    //接口定义‘public’访问属性方法,无需实现方法 
    public function eat( $foods ); 
}
Copy after login

Human (Animl) class implementation interface:

class Human implements Action(){ 
    //实现接口,必须提供接口中定义的方法 
    public function eat( $foods){ 
        echo "Human eat {$foods}"; 
    } 
} 
#Animal类 
class  Animal implements Action(){ 
    public function eat( $foods){ 
        echo "Animal eat {$foods}"; 
    } 
}
Copy after login

The above is the detailed content of How to make an interface in php. 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