Table of Contents
(1) Understand the definition of interface in PHP (What)
(5), specific code
(6) Apply what you have learned
(7) Summary
Home Backend Development PHP Tutorial Detailed explanation of PHP object-oriented interface (code example)

Detailed explanation of PHP object-oriented interface (code example)

May 26, 2020 am 10:12 AM
object-oriented

Objectives of this article:

1. Understand the definition of interfaces in PHP

2. Understand the role of interfaces in PHP

3. Understand PHP Usage scenarios of interfaces in PHP

4. Understand the specific implementation of interfaces in PHP

Still inheriting the previous learning ideas. When we learn a piece of knowledge, we should learn based on the ideas of 3w1h

(1) Understand the definition of interface in PHP (What)

Definition: The interface is the common behavior of different types of <span style="background-color: rgb(255, 0, 0); color: rgb(255, 255, 255); border: 1px solid rgb(0, 0, 0);"></span><span style="color: rgb(0, 0, 0);"> </span>## is defined, and then different functions are implemented in different classes<span style="color: rgb(0, 0, 0);"></span>

Or we can understand it as A unified specification for things, which stipulates what behaviors a certain thing must have. For example, the human interface stipulates some methods that people must have, such as eating, drinking, defecating, peeing, and walking<span style="color: rgb(0, 0, 0);">, <span style="color: rgb(0, 0, 0); font-family: monospace;">Speaking</span>, <span style="color: rgb(0, 0, 0); font-family: monospace;">Blinking</span>, <span style="color: rgb(0, 0, 0); font-family: monospace;">Sleeping</span>, <span style="color: rgb(0, 0, 0); font-family: monospace;">Thinking, etc. Without any of these behaviors, you are not a normal person</span></span>

(2) Understand the role of interfaces in PHP (Why)

Role:

1. Standardize the code:

Defining the interface is conducive to the standardization of the code: especially for For some large-scale projects, with a unified interface, on the one hand, developers can have a clear understanding and know exactly what services they want to implement at a glance at the interface; at the same time, it can also prevent naming inconsistencies caused by developers naming arbitrarily. Clarity and code confusion affect development efficiency.

2. Improved code maintainability: For example, if you want to make a distribution mall program, there is a distribution class in it, which is mainly responsible for the distribution function. At the beginning, you may Encapsulate some of the distribution functions you just thought of into this distribution class. But as time goes by, you may find that the existing class can no longer meet your new needs, and then you need to redesign this class. But the worst case scenario is that you will find that this class seems to be useless at this moment. It is of no use, but this class may be referenced in other places in the code. If it is completely modified, it will cause a lot of trouble. But if you define it as an interface at the beginning, put some of the main functions of distribution in the interface, and then define another distribution class to specifically implement these interfaces, then you only need to use this interface to reference the already implemented Just use the interface-related classes. Even if you want to change it in the future, it will just refer to another class. This can improve the maintainability and scalability of the code.

3. Make the code more cohesive and low-coupled

(3) Understand the usage scenarios of interfaces in PHP (Where)

Scenario: Combined with its function, the usage scenario is basically as follows

1. If we want to ensure that a class is more standardized, we can define an interface for this class, then all the interfaces that inherit this interface All classes must implement the methods defined in the interface

2. If we want to improve the maintainability, reusability and scalability of the code, we can also consider it, especially when participating in the development of large projects When doing this, you must first consider which interfaces need to be defined first. This is equivalent to determining the specifications first. Once the specifications are determined, efficiency will be improved when division of labor and cooperation are done

(4) , Understand the specific implementation of interfaces in PHP (How)

Summary:


1. Definition of interface interface interface name { }

2. Methods in the interface There is no {}, which means that the method inside does not have a specific implementation part

3. The definition of the class implementation interface is through the keyword implements, such as class A implementations interface {}

4. Once a class wants to implement an interface, it must implement all the methods defined by the interface

5. The interface cannot be instantiated

6. Use instanceof to determine whether an instance of a class is An interface is implemented, such as A object instance instanceof B interface

If true is returned, it means that the class corresponding to the A object instance implements B interface

7. An interface can be inherited through extends Another interface

8. When a class wants to implement a sub-interface, it must not only implement the methods in the sub-interface, but also implement all the methods of the parent interface

Each summary is based on practice Well, let’s demonstrate the above summary one by one through specific codes

(5), specific code

1, case one

Practice goals:

1. Definition of interface interface interface name { }

2. There is no {} in the method in the interface, that is to say, the method inside There is no specific implementation part

<?php
//接口定义
interface Action{
    public function eat();
    public function walk();
    public function sleep();
}
?>
Copy after login

Run result: It is blank and no error is reported

2. Case 2

Practical goals:

1. A class must implement the definition of an interface through the keyword implements, such as class A implements interface {}

2. Once a class wants to implement an interface, it must implement the interface definition. All methods

<?php
//接口定义
interface Action{
    public function eat();
    public function walk();
    public function sleep();
}
//定义实现接口的类
class Monkey implements Action{
    //一旦要实现一个接口,就必须要实现接口里面的所有方法
    public function eat(){}
    public function walk(){}
    public function sleep(){}
}
$monkey = new Monkey();

?>
Copy after login

The running result of methods that do not implement the interface is:

Fatal error: Class Monkey contains 3 abstract methods and must therefore be declared abstract or implement the remaining methods (Action:: eat, Action::walk, Action::sleep) in D:\E-class\class-code\classing\index.php on line 11

The running result of implementing the interface is:

The blank description is correct

3. Case 3

Practice goals:

1. The interface cannot be instantiated The result of

<?php
//接口定义
interface Action{
    public function eat();
    public function walk();
    public function sleep();
}
$action = new Action();

?>
Copy after login

is:

Fatal error: Uncaught Error: Cannot instantiate interface Action in D:\E-class\class-code\classing\index.php:9 Stack trace: #0 {main} thrown in D:\E-class\class-code\classing\index.php on line 9

4、Case 4

Practical goals:

1. Use instanceof to determine whether an instance of a class implements an interface, such as A object instance instance of B interface

If true is returned, it means that the class corresponding to the A object instance implements the B interface

<?php
//接口定义
interface Action{
    public function eat();
    public function walk();
    public function sleep();
}
//定义实现接口的类
class Monkey implements Action{
    public function eat(){}
    public function walk(){}
    public function sleep(){}
}
$monkey = new Monkey();
print_r( $monkey instanceof Action );
?>
Copy after login

The running result is: 1

5, Case 5

Practical goals:

1. One interface can inherit another interface through extends

<?php
//接口定义
interface Action{
    public function eat();
    public function walk();
    public function sleep();
}
//接口继承
interface HigherAction extends Action{
    public function talk();
    public function think();
}

?>
Copy after login

6. Case 6

Practical goals:

1. When a class wants to implement a sub-interface, it must not only implement the methods in the sub-interface, but also implement all the methods of the parent interface

<?php
//接口定义
interface Action{
    public function eat();
    public function walk();
    public function sleep();
}
//接口继承
interface HigherAction extends Action{
    public function talk();
    public function think();
}
//定义实现子接口的类
class Human implements HigherAction{
    public function eat(){}
    public function talk(){}
    public function walk(){}
    public function sleep(){}
    public function think(){}
}
$human = new Human();

?>
Copy after login

When When the Human class only implements the two methods of HigherAction, the running result is:

Fatal error: Class Human contains 3 abstract methods and must therefore be declared abstract or implement the remaining methods (HigherAction::think, Action: :walk, Action::sleep) in D:\E-class\class-code\classing\index.php on line 14

When the Human class implements all methods of HigherAction and Action, the running result is:

is blank, the explanation is correct

(6) Apply what you have learned

Question: The distribution system must be familiar to many people, but the distribution system There are also many types, such as the common 2-level distribution that is not illegal, and the 3-level distribution that is slightly illegal. In fact, there are more complicated distribution systems, but no matter what kind of distribution system, they all have similar methods. We hope Make these methods into an interface, and then hand over the specific implementation to two classes: level 2 distribution and level 3 distribution. How to do it?

Idea analysis:

1. Think about the public methods of distribution first

2. Encapsulate these methods into the distribution interface

3. Definition 2 Classes, let these two classes implement the distribution interface respectively

Specific code:

<?php
//分销接口定义
interface Commission{
    //获取会员的直接上级
    public function getParent($uid);
    //获取会员的当期级别
    public function getLevel($uid);
    //获取会员的累计佣金
    public function getTotalCommission($uid);
    //获取会员当期可提现佣金
    public function getCurrCommission($uid);
    //获取会员的累计提现佣金
    public function getTotalApplyPrice($uid);
}
//2级分销
class TwoLevelCommission implements Commission{
    //获取会员的直接上级
    public function getParent($uid){}
    //获取会员的当期级别
    public function getLevel($uid){}
    //获取会员的累计佣金
    public function getTotalCommission($uid){}
    //获取会员当期可提现佣金
    public function getCurrCommission($uid){}
    //获取会员的累计提现佣金
    public function getTotalApplyPrice($uid){}
}
//3级分销
class ThreeLevelCommission implements Commission{
    //获取会员的直接上级
    public function getParent($uid){}
    //获取会员的当期级别
    public function getLevel($uid){}
    //获取会员的累计佣金
    public function getTotalCommission($uid){}
    //获取会员当期可提现佣金
    public function getCurrCommission($uid){}
    //获取会员的累计提现佣金
    public function getTotalApplyPrice($uid){}
}
?>
Copy after login

(7) Summary

1. This article mainly talks about the interface Definition, function and implementation

I hope this article can bring some help to everyone, thank you! ! !

The above is the detailed content of Detailed explanation of PHP object-oriented interface (code example). For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement object-oriented event-driven programming using Go language How to implement object-oriented event-driven programming using Go language Jul 20, 2023 pm 10:36 PM

How to use Go language to implement object-oriented event-driven programming Introduction: The object-oriented programming paradigm is widely used in software development, and event-driven programming is a common programming model that realizes the program flow through the triggering and processing of events. control. This article will introduce how to implement object-oriented event-driven programming using Go language and provide code examples. 1. The concept of event-driven programming Event-driven programming is a programming model based on events and messages, which transfers the flow control of the program to the triggering and processing of events. in event driven

What is the importance of @JsonIdentityInfo annotation using Jackson in Java? What is the importance of @JsonIdentityInfo annotation using Jackson in Java? Sep 23, 2023 am 09:37 AM

The @JsonIdentityInfo annotation is used when an object has a parent-child relationship in the Jackson library. The @JsonIdentityInfo annotation is used to indicate object identity during serialization and deserialization. ObjectIdGenerators.PropertyGenerator is an abstract placeholder class used to represent situations where the object identifier to be used comes from a POJO property. Syntax@Target(value={ANNOTATION_TYPE,TYPE,FIELD,METHOD,PARAMETER})@Retention(value=RUNTIME)public

Explore object-oriented programming in Go Explore object-oriented programming in Go Apr 04, 2024 am 10:39 AM

Go language supports object-oriented programming through type definition and method association. It does not support traditional inheritance, but is implemented through composition. Interfaces provide consistency between types and allow abstract methods to be defined. Practical cases show how to use OOP to manage customer information, including creating, obtaining, updating and deleting customer operations.

Analysis of object-oriented features of Go language Analysis of object-oriented features of Go language Apr 04, 2024 am 11:18 AM

The Go language supports object-oriented programming, defining objects through structs, defining methods using pointer receivers, and implementing polymorphism through interfaces. The object-oriented features provide code reuse, maintainability and encapsulation in the Go language, but there are also limitations such as the lack of traditional concepts of classes and inheritance and method signature casts.

Analyzing the Flyweight Pattern in PHP Object-Oriented Programming Analyzing the Flyweight Pattern in PHP Object-Oriented Programming Aug 14, 2023 pm 05:25 PM

Analyzing the Flyweight Pattern in PHP Object-Oriented Programming In object-oriented programming, design pattern is a commonly used software design method, which can improve the readability, maintainability and scalability of the code. Flyweight pattern is one of the design patterns that reduces memory overhead by sharing objects. This article will explore how to use flyweight mode in PHP to improve program performance. What is flyweight mode? Flyweight pattern is a structural design pattern whose purpose is to share the same object between different objects.

PHP Advanced Features: Best Practices in Object-Oriented Programming PHP Advanced Features: Best Practices in Object-Oriented Programming Jun 05, 2024 pm 09:39 PM

OOP best practices in PHP include naming conventions, interfaces and abstract classes, inheritance and polymorphism, and dependency injection. Practical cases include: using warehouse mode to manage data and using strategy mode to implement sorting.

Are there any class-like object-oriented features in Golang? Are there any class-like object-oriented features in Golang? Mar 19, 2024 pm 02:51 PM

There is no concept of a class in the traditional sense in Golang (Go language), but it provides a data type called a structure, through which object-oriented features similar to classes can be achieved. In this article, we'll explain how to use structures to implement object-oriented features and provide concrete code examples. Definition and use of structures First, let's take a look at the definition and use of structures. In Golang, structures can be defined through the type keyword and then used where needed. Structures can contain attributes

C# development experience sharing: object-oriented programming and design principles C# development experience sharing: object-oriented programming and design principles Nov 22, 2023 am 08:18 AM

C# (CSharp) is a powerful and popular object-oriented programming language that is widely used in the field of software development. During the C# development process, it is very important to understand the basic concepts and design principles of object-oriented programming (OOP). Object-oriented programming is a programming paradigm that abstracts things in the real world into objects and implements system functions through interactions between objects. In C#, classes are the basic building blocks of object-oriented programming and are used to define the properties and behavior of objects. When developing C#, there are several important design principles

See all articles