Some summaries on the use of PHP interfaces
PHP’s interface has been controversial from beginning to end. Some people say that the interface is very good, while others say that the interface is useless. First of all, you must understand what the criteria are for judging whether something tastes good or bad. Undoubtedly, this is compared with Java/C++. In the above example and discussion, PHP's interface is insufficient in "contract-oriented programming" and does not play its due role.
In fact, the declaration of the machine class should be in front of the plain class. The interface provides a set of specifications, which are provided by the system, then the machine class provides a set of APIs for the interface and implements them, and finally the custom class. In Java, the reason why interfaces are popular (multi-threaded runable interface, container collection interface, etc.) is because the system does the first two parts of the work for us, and programmers only need to write specific implementation classes to ensure that The interface is available and controllable.
Why use interfaces? What are the benefits of interfaces? The interface itself does not provide an implementation, only a specification. If we know that a class implements an interface, then we know the methods that can be called on the interface. We only need to know these.
In PHP, the semantics of interfaces are limited, and there are not many places to use interfaces. Interfaces in PHP can be reduced to design documents, which serve as a basic contract for the team. The code is as follows:
<?php interface Cache { /** * describe:缓存管理,项目经理定义接口,技术人员负责实现 */ const maxKey = 10000; //最大换存量 public function getCache($key); //获取缓存 public function setCache($key,$value); //设置缓存 public function flush(); //清空缓存 }
Since PHP is weakly typed and emphasizes flexibility, it is not recommended to use interfaces on a large scale, but to only use interfaces in some "kernel" codes, because the interfaces in PHP have lost many interfaces that should have semantics. From a semantic perspective, you can use abstract classes more. As for the comparison between abstract classes and interfaces, I won’t go into details.
In addition, PHP5 has made many enhancements to the special features of Object-oriented, among which there is an attempt to SPL (labeled PHP library). Some interfaces are implemented in SPL, the most important of which is iterator Iterator interface, by implementing this interface, the object can be used in the foreach structure, so that the usage form is relatively unified. For example, there is a DirectoryIterator class in SPL. This class integrates the SplFileInfo class and implements the three interfaces Iterator, Traversable, and SeekableIterator. Then an instance of this class can obtain all the functions of the parent class SplFileInfo, and also Able to implement the operations shown in Iterator interface.
The prototype of the Iterator interface is as follows:
* current() This methodreturns the current index's value. You are solely responsible for tracking what thecurrent index is as the interface does not do this for you. *key() This method returns the value of the current index's key. For foreach loops this is extremely important so that the key value can be populated. *next() This method moves the internal index forward one entry. *rewind() This method should reset the internal index to the first element. *valid() This method should return true or false if there is a current element. It is called after rewind() or next().
If a class declares to implement Iterator, it must implement these five methods. If these five methods are implemented, then it can be easily implemented. Instances of the class are iterated over. Here, the reason why the DirectoryIterator class can be used is because the system has implemented the Iterator interface, so it can be used as follows:
<?php $dir = new DirectoryIterator(dirname(FILE)); foreach ($dir as $fileInfo) { if(!$fileInfo->isDir()) { echo $fileInfo->getFilename(),"\t",$fileInfo->getSize(),PHP_EOL; } }
It is conceivable that if you do not use the DirectoryIterator class but implement it yourself, not only the code The volume has increased, and the style during looping is no longer uniform. If the class you write also implements the Iterator interface, it can work like an Iterator.
Why can a class’s object be used as a foreach object as long as it implements the Iterator? In fact, the reason is very simple. When using foreach syntax on a PHP instance object, it will check whether the instance implements the Iterator interface. If it does, the foreach statement will be simulated through built-in methods or using methods in the implementation class. Is this the same as before? Is the implementation of the toString method mentioned similar? In fact, the toString method is a disguised implementation of the interface. The interface is like this. The interface itself does nothing. The system quietly implements the behavior of the interface internally, so as long as you implement this interface, you can use the methods provided by the interface. This is the "plug and play" idea of interfaces
We all know that interfaces are a disguised implementation of multiple integrations, and when talking about inheritance, we mentioned Traits used to implement mix-ins , in fact, traits can be regarded as an enhanced version of the interface.
Look at the following code:
<?php trait Hello { public function sayHello() { echo 'Hello '; } } trait World { public function sayWorld() { echo 'Word'; } } class MyHelloWorld { use Hello, World; public function sayExclamationMark() { echo '!'; } } $o = new MyHelloWorld(); $o->sayHello(); $o->sayWorld(); $o->sayExclamationMark();
The results of the above code are as follows:
Hello Word!
MyHelloWorld here implements two traits at the same time, so that it can call two traits separately. Code snippets in Traits. As you can see from the code, Traits are very similar to interfaces. The difference is that Traits can import interfaces containing code. In a sense, traits and interfaces are a disguised implementation of "multiple integration".
Summarize several concepts about interfaces:
Interfaces exist as a specification and contract. As a specification, the interface should ensure usability; as a contract interface, it should ensure controllability.
The interface is just a statement. Once the interface keyword is used, it should be implemented. It can be implemented by the programmer (external interface) or by the system (internal interface). The interface itself does nothing, but it can tell us what it can do.
There are two shortcomings in the interfaces in PHP. One is that there are no contract restrictions, and the other is that there are not enough internal interfaces.
The interface is actually very simple, but the various applications of the interface are very flexible. A large part of Design Pattern also revolves around the interface.
The above is the detailed content of Some summaries on the use of PHP interfaces. For more information, please follow other related articles on the PHP Chinese website!

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

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

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

Hot Topics

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.
