ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
## **[Traversable(遍历)接口](https://www.php.net/manual/zh/class.traversable.php#class.traversable)** >[danger]这是一个无法在 PHP 脚本中实现的内部引擎接口。无法被单独实现的基本抽象接口。相反它必须由**IteratorAggregate**或**Iterator**接口实现 ``` Traversable{ } ``` 目前为止只有instanceof能被我们使用 检测一个类(或者数组)是否可以使用[foreach](https://www.php.net/manual/zh/control-structures.foreach.php)进行遍历的接口【php7.1+可以使用is_iterable来检查】 ``` if ( !($myobj instanceof \Traversable) ) {     print "myobj is NOT Traversable"; } ``` ``` //注意:虽然对象和数组可以由foreach遍历,但它们不实现“可遍历”,因此不能使用instanceof Traversable来检查foreach $myarray = array('one', 'two', 'three'); $myobj = (object)$myarray; if ($myarray instanceof Traversable) { echo '[myarray]yes'; } //php7.1+可以使用is_iterable来检查数组或者实现Traversable的类的迭代性 if (is_iterable($myarray)) { echo '$myarray is_iterable'; } if ($myobj instanceof Traversable) { echo '[myobj]yes'; } if (is_iterable($myobj)) { echo '$myobj is_iterable'; } //那么instanceof Traversable在什么情况下生效(实现Iterator或IteratorAggregate接口的类) class A { } class B implements Iterator{//Iterator继承Traversable public function current (){} //返回当前产生的值 public function key (){} //返回当前产生的键 public function next (){} // 生成器继续执行 public function rewind (){} //重置迭代器 public function valid (){} //检查迭代器是否被关闭 } $a=new A(); $b=new B(); if ($a instanceof Traversable) { echo '[A]yes'; } if ($b instanceof Traversable) { echo '[B]yes'; } //不能直接实现Traversable会报致命错误 class S implements Traversable {} ``` 结果: ``` $myarray is_iterable [B]yes Fatal error: Class S must implement interface Traversable as part of either Iterator or IteratorAggregate in Unknownon line 0 ```