


Detailed 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>
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: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!

PHP remains a powerful and widely used tool in modern programming, especially in the field of web development. 1) PHP is easy to use and seamlessly integrated with databases, and is the first choice for many developers. 2) It supports dynamic content generation and object-oriented programming, suitable for quickly creating and maintaining websites. 3) PHP's performance can be improved by caching and optimizing database queries, and its extensive community and rich ecosystem make it still important in today's technology stack.

In PHP, weak references are implemented through the WeakReference class and will not prevent the garbage collector from reclaiming objects. Weak references are suitable for scenarios such as caching systems and event listeners. It should be noted that it cannot guarantee the survival of objects and that garbage collection may be delayed.

The \_\_invoke method allows objects to be called like functions. 1. Define the \_\_invoke method so that the object can be called. 2. When using the $obj(...) syntax, PHP will execute the \_\_invoke method. 3. Suitable for scenarios such as logging and calculator, improving code flexibility and readability.

Fibers was introduced in PHP8.1, improving concurrent processing capabilities. 1) Fibers is a lightweight concurrency model similar to coroutines. 2) They allow developers to manually control the execution flow of tasks and are suitable for handling I/O-intensive tasks. 3) Using Fibers can write more efficient and responsive code.

The PHP community provides rich resources and support to help developers grow. 1) Resources include official documentation, tutorials, blogs and open source projects such as Laravel and Symfony. 2) Support can be obtained through StackOverflow, Reddit and Slack channels. 3) Development trends can be learned by following RFC. 4) Integration into the community can be achieved through active participation, contribution to code and learning sharing.

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP is not dying, but constantly adapting and evolving. 1) PHP has undergone multiple version iterations since 1994 to adapt to new technology trends. 2) It is currently widely used in e-commerce, content management systems and other fields. 3) PHP8 introduces JIT compiler and other functions to improve performance and modernization. 4) Use OPcache and follow PSR-12 standards to optimize performance and code quality.

The future of PHP will be achieved by adapting to new technology trends and introducing innovative features: 1) Adapting to cloud computing, containerization and microservice architectures, supporting Docker and Kubernetes; 2) introducing JIT compilers and enumeration types to improve performance and data processing efficiency; 3) Continuously optimize performance and promote best practices.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Chinese version
Chinese version, very easy to use

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),

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function