Some summary of the use of PHP interface

Source: Internet
Author: User
Tags spl rewind traits
PHP interface has been controversial from beginning to finish, some people say interface is very good, some people say interface like chicken. The first thing to understand is that good drinking is not the standard of judgment. Undoubtedly, this is compared with java/c++. In the above example, and the discussion of the PHP interface in "Contract-oriented programming" is insufficient, and did not play its rightful role.

In fact, the machine class declaration should precede the plain class. The interface provides a set of specifications, which are provided by the system, and then the machine class provides a set of APIs for the interface and is implemented, and finally the custom class. In Java, the interface is prevalent (multi-threaded Runable interface, container collection interface, etc.) is because the system for us to do the first two parts of the work, and the programmer, just to write the specific implementation class, you can ensure that the interface can be controlled.

Why use an interface? What are the benefits of an interface? The interface itself does not provide implementations, but provides a specification. If we know that a class implements an interface, then we know the methods that can invoke that interface, and that's all we need to know.

PHP, the semantics of the interface is limited, the use of the interface is not much, the interface in PHP can be played down as a design document, the role of a team basic contract, the code is as follows:

<?phpinterface cache{/** * Describe: Cache management, the project manager defines the interface, the technician is responsible for implementing the */    const MAXKEY = 10000;                  Maximum stock change public    function GetCache ($key);        Gets the cache public    function Setcache ($key, $value);//Set Cache public    function flush ();               Empty Cache}


Because PHP is a weak type and emphasizes flexibility, it is not recommended to use interfaces on a large scale, but only in some "kernel" code, because interfaces in PHP have lost the semantics that many interfaces should have. In terms of semantics, you can use abstract classes more frequently. As for the comparison of abstract classes and interfaces, do not repeat them.

In addition, PHP5 has done a lot of enhancements to the object-oriented special, in which there is a SPL (annotated PHP Library) attempt to implement some interfaces in SPL, the most important of which is the iterator iterator interface, by implementing this interface, the object can be used in the foreach structure, Thus in the use of formal comparison of unity. such as SPL in a Directoryiterator class, this class in the integration of Splfileinfo class, the implementation of iterator, traversable, seekableiterator these three interfaces, The instance of this class can obtain all the functions of the parent class Splfileinfo, and can also implement the actions shown by the iterator interface.

The iterator interface is prototyped as follows:

* Current () This methodreturns the current    index ' s value.  You were solely responsible for tracking what Thecurrent index is as the interface does does this for You.*key () this    method returns the value of the current index ' s key. For foreach loops This is extremely important so, 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 implementation iterator, you must implement these five methods, and if you implement these five methods, you can easily iterate over the instances of the class. Here, the Directoryiterator class can be used 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;    }}

Can imagine, if not directoryiterator class, but the implementation of their own, not only the amount of code increases, but also the style of the cycle is not unified. If you write a class that also implements the iterator interface, you can work like iterator.

Why does a class implement a iterator iterator so that its object can be used as a foreach object? In fact, the reason is very simple, when using the foreach syntax for a php instance object, it is checked that the instance does not implement the iterator interface, and if it is implemented, it will simulate the foreach statement through a built-in method or using the method in the implementation class, which is not the same as the previously mentioned ToString is the implementation of the method similar? In fact, the ToString method is a disguised implementation of the interface. Interface is like this, the interface itself does nothing, the system quietly in the internal implementation of the interface behavior, so long as the implementation of this interface, you can use the method provided by the interface. This is the interface "Plug and Play" thinking

As we all know, interfaces are a disguised implementation of multiple integration, and when it comes to inheritance, we refer to the traits used to implement mixed (minxin), in fact, traits can be considered an enhanced version of the interface.

Look at the following code:

<?phptrait 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 above code runs the following results:

Hello word!

The Myhelloworld here also implements two traits, allowing it to invoke code snippets in two traits respectively. As you can see from the code, traits and interfaces are similar, unlike traits, which can import interfaces that contain code. In a sense, traits and interfaces are a disguised implementation of "multi-integration".

Summarize several concepts about interfaces:

    • Interfaces exist as a specification and contract. As a specification, the interface should be guaranteed to be available, and as a contractual interface it should ensure controllability,

    • The interface is just a declaration and should be implemented once the interface keyword is used. Can be implemented by the programmer (external interface) or by the system (internal interface). The interface itself does nothing, but he can count us what it can do.

    • There are two shortcomings in PHP interface, there is no contract limit for a moment, and the second is the lack of enough internal interfaces.

The

interface is very simple, but the various applications of the interface are flexible, and a large part of the design pattern is developed around the interface.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.