Usage of the PHP detection interface Traversable

Source: Internet
Author: User

Usage of the PHP detection interface Traversable

This example describes how to use the PHP detection interface Traversable. We will share this with you for your reference. The details are as follows:

Traversable is used to check whether a class can be traversed using foreach. This is an internal engine interface that cannot be implemented in PHP scripts. In actual programming, we use the Iterator interface or the IteratorAggregate interface to implement traversal.

Interface Abstract:

Traversable {}

An important use of Traversable is to determine whether a class can be traversed. The following is an official example:

<? Php if (! Is_array ($ items )&&! $ Items instanceof Traversable) // Throw exception here?>

It should be noted that arrays and objects can be traversed through foreach, but they do not implement the Traversable interface, so it is not an example of Traversable:

<? Php $ array = [1, 2]; $ obj = (object) $ array; var_dump ($ array instanceof \ Traversable); var_dump ($ obj instanceof \ Traversable);?>

The above code output:

Boolean falseboolean false

Note:

When the class does not implement the Iterator interface or the IteratorAggregate interface, executing the foreach traversal will output all the visible attributes that can be accessed by the class.

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.