Detailed explanation of PHP detection interface Traversable usage

  • 2021-08-31 07:26:52
  • OfStack

This article illustrates the usage of PHP detection interface Traversable. Share it for your reference, as follows:

Traversable is used to detect whether a class can be traversed by foreach, which is an internal engine interface that cannot be implemented in PHP script. In actual programming, we use Iterator interface or IteratorAggregate interface to realize traversal.

Interface Summary:

Traversable {

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

  if( !is_array( $items ) && !$items instanceof Traversable )
    //Throw exception here

Note that arrays and objects can be traversed through foreach, but they do not implement the Traversable interface, so they are not examples of Traversable:

$obj = (object) $array;
var_dump($array instanceof \Traversable);
var_dump($obj instanceof \Traversable);

The above code output:

boolean false
boolean false

Supplementary notes:

Class does not implement an Iterator interface or an IteratorAggregate interface, performing an foreach traversal outputs all visible properties it can access

For more readers interested in PHP related content, please check the topics on this site: "Introduction to php Object-Oriented Programming", "Encyclopedia of PHP Array (Array) Operation Skills", "Introduction to PHP Basic Syntax", "Summary of PHP Operation and Operator Usage", "Summary of php String (string) Usage", "Introduction to php+mysql Database Operation" and "Summary of php Common Database Operation Skills"

I hope this article is helpful to everyone's PHP programming.

Related articles: