Home > Backend Development > PHP Tutorial > PHP - Detailed explanation of Traversable interface

PHP - Detailed explanation of Traversable interface

WBOY
Release: 2016-07-29 08:57:02
Original
1218 people have browsed it

Traversable is used to detect 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 IteratorAggregate interface to implement traversal.

Interface summary:

Traversable {
}
Copy after login

An important use of Traversable is to determine whether a class can be traversed. The following is the official example:
<?php
    if( !is_array( $items ) && !$items instanceof Traversable )
        //Throw exception here
?>
Copy after login

It should be noted that arrays and objects can be traversed through foreach, but they do not implement the Traversable interface, so Example that is not Traversable:
<?php
$array=[1,2,3];
$obj = (object) $array;
var_dump($array instanceof \Traversable);
var_dump($obj instanceof \Traversable);
?>
Copy after login
The above code output:
<small>boolean</small><span>false</span>
Copy after login
rrree added:

When the class does not implement the Iterator interface or the IteratorAggregate interface, executing foreach traversal will output all the visible properties it can access

The above introduces the detailed explanation of the PHP - Traversable interface, including the relevant aspects. I hope it will be helpful to friends who are interested in PHP tutorials.

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template