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!

TomodifydatainaPHPsession,startthesessionwithsession_start(),thenuse$_SESSIONtoset,modify,orremovevariables.1)Startthesession.2)Setormodifysessionvariablesusing$_SESSION.3)Removevariableswithunset().4)Clearallvariableswithsession_unset().5)Destroythe

Arrays can be stored in PHP sessions. 1. Start the session and use session_start(). 2. Create an array and store it in $_SESSION. 3. Retrieve the array through $_SESSION. 4. Optimize session data to improve performance.

PHP session garbage collection is triggered through a probability mechanism to clean up expired session data. 1) Set the trigger probability and session life cycle in the configuration file; 2) You can use cron tasks to optimize high-load applications; 3) You need to balance the garbage collection frequency and performance to avoid data loss.

Tracking user session activities in PHP is implemented through session management. 1) Use session_start() to start the session. 2) Store and access data through the $_SESSION array. 3) Call session_destroy() to end the session. Session tracking is used for user behavior analysis, security monitoring, and performance optimization.

Using databases to store PHP session data can improve performance and scalability. 1) Configure MySQL to store session data: Set up the session processor in php.ini or PHP code. 2) Implement custom session processor: define open, close, read, write and other functions to interact with the database. 3) Optimization and best practices: Use indexing, caching, data compression and distributed storage to improve performance.

PHPsessionstrackuserdataacrossmultiplepagerequestsusingauniqueIDstoredinacookie.Here'showtomanagethemeffectively:1)Startasessionwithsession_start()andstoredatain$_SESSION.2)RegeneratethesessionIDafterloginwithsession_regenerate_id(true)topreventsessi

In PHP, iterating through session data can be achieved through the following steps: 1. Start the session using session_start(). 2. Iterate through foreach loop through all key-value pairs in the $_SESSION array. 3. When processing complex data structures, use is_array() or is_object() functions and use print_r() to output detailed information. 4. When optimizing traversal, paging can be used to avoid processing large amounts of data at one time. This will help you manage and use PHP session data more efficiently in your actual project.

The session realizes user authentication through the server-side state management mechanism. 1) Session creation and generation of unique IDs, 2) IDs are passed through cookies, 3) Server stores and accesses session data through IDs, 4) User authentication and status management are realized, improving application security and user experience.


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

Atom editor mac version download
The most popular open source editor

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver CS6
Visual web development tools

SublimeText3 Chinese version
Chinese version, very easy to use

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
