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.