Home  >  Article  >  Backend Development  >  PHP detection interface Traversable usage example

PHP detection interface Traversable usage example

小云云
小云云Original
2017-12-29 16:48:311202browse

This article mainly introduces the usage of the PHP detection interface Traversable, and analyzes the relevant operating skills of the Traversable interface detection traversal function in the form of examples. Friends in need can refer to it. I hope it can help everyone.

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 {
}

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 they are not Traversable examples:

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

The above code output:

boolean false
boolean false

Additional explanation:

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

Related recommendations:

php—Traversable interface

2Traversable( Traversable) interface

PHP - Traversable interface detailed explanation

The above is the detailed content of PHP detection interface Traversable usage example. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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