search
HomeBackend DevelopmentPHP TutorialDetailed explanation of PHP object-oriented interface (code example)

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();
}
?>

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();

?>

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();

?>

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 );
?>

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();
}

?>

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();

?>

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){}
}
?>

(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
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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),