Home Backend Development PHP Tutorial Some summaries on the use of PHP interfaces

Some summaries on the use of PHP interfaces

Jul 03, 2017 am 10:40 AM
php Summarize

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();               //清空缓存
}
Copy after login


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&#39;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&#39;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().
Copy after login

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;
    }
}
Copy after login

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 &#39;Hello &#39;;
    }
}

trait World
{
    public function sayWorld()
    {
        echo &#39;Word&#39;;
    }
}

class MyHelloWorld
{
    use Hello, World;
    public function sayExclamationMark()
    {
        echo &#39;!&#39;;
    }
}

$o = new MyHelloWorld();

$o->sayHello();
$o->sayWorld();
$o->sayExclamationMark();
Copy after login

The results of the above code are as follows:

Hello Word!
Copy after login

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!

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

Video Face Swap

Video Face Swap

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

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 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)

Hot Topics

Java Tutorial
1668
14
PHP Tutorial
1273
29
C# Tutorial
1256
24
PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

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 and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 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 vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

See all articles