Thinking of PHP interface

Source: Internet
Author: User
Tags spl

There is a SPL (Standard PHP Library) attempt, the implementation of some interfaces in SPL, the most important of which is the iterator iterator interface, by implementing this interface, you can make the object can be used in the foreach structure, Thus in the use of formal comparison. For example, there is a directoryiterator class in SPL, which implements the iterator,traversable,seekableiterator three interfaces while inheriting the Splfileinfo class. Then the instance of this class can get all the functions of the parent class Splfileinfo, but also can realize the operation that the iterator interface shows.

The directory class can be used because the system has implemented the iterator interface, so it can be used as follows:
$dir = new Directoryiterator (dirname (__file__)), foreach ($dir as $fileinfo) {    if (! $fileinfo->isdir ())    {        echo $fileinfo->getfilename (), "\ T", $fileinfo->getsize (), Php_eol;    }}
As you can imagine, if you do not use the Directoryiterator class, but your own implementation, not only the amount of code increases, but also the loop style is not unified. If the class you write also implements the iterator interface, Then you can work like iterator. Why is a class as long as the iterator iterator is implemented and its object can be used as a foreach object? The reason is simple, when using the foreach syntax for a php instance object, Will check if this instance implements the iterator interface and, if implemented, simulates a foreach statement through a built-in method or by using a method in the implementation class. This is similar to the __tostring approach, in fact, the __tostring method is a disguised implementation of the interface.

Thinking of PHP interface

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.