SunshinePHP Developer Conference 2015

Traversable(遍历)接口

(No version information available, might only be in Git)

简介

检测一个类是否可以使用 foreach 进行遍历的接口。

无法被单独实现的基本抽象接口。相反它必须由 IteratorAggregateIterator 接口实现。

Note:

实现此接口的内建类可以使用 foreach 进行遍历而无需实现 IteratorAggregateIterator 接口。

Note:

这是一个无法在 PHP 脚本中实现的内部引擎接口。IteratorAggregateIterator 接口可以用来代替它。

接口摘要

Traversable {
}

这个接口没有任何方法,它的作用仅仅是作为所有可遍历类的基本接口。

add a note add a note

User Contributed Notes 2 notes

up
35
kevinpeno at gmail dot com
4 years ago
While you cannot implement this interface, you can use it in your checks to determine if something is usable in for each. Here is what I use if I'm expecting something that must be iterable via foreach.

<?php
   
if( !is_array( $items ) && !$items instanceof Traversable )
       
//Throw exception here
?>
up
-30
mathdegiovani at gmail dot com
7 months ago
Note that instanceof Traversable does not work for stdclass objects, so if you are this check (as @kevinpeno) to decide whether you can iterate, it will fail for direct instances.

In particular:

<?php

$obj
= new stdclass();
$obj->prop = 'hello';
var_dump($obj instanceof Traversable);
//outputs bool(false)
?>

My own solution is to check whether the object also descends from stdclass, but that also fails to catch some objects that are iterable.
To Top