spl的基础接口里面定义了最常用的接口

Countable 继承了该接口的类可以直接调用count()得到元素个数

<?php

date_default_timezone_set('PRC');

//继承了implements Countable接口,实现了count()方法  就可以使用count($obj)进行计算

class CountMe implements Countable{

protected $_mycount = 3;

public function count(){

return $this->_mycount;

}

}

$obj = new CountMe();

echo count($obj);

?>

OuterIterator OuterIterator 如果想对迭代器进行一定的处理之后再返回,可以用这个接口

IteratorIterator类是OuterIterator的实现,扩展的时候可以直接继承IteratorItreator

<?php

date_default_timezone_set('PRC');

$array = ["value1","value2","value3","value4"];

$outerObj = new OuterImpl(new ArrayIterator($array));

foreach ($outerObj as $key => $value) {

echo "++".$key."--".$value."<br>";

}

class OuterImpl extends IteratorIterator{

public function current(){

return parent::current()."tail";

}

public function key(){

return "Pre".parent::key();

}

}

?>

RecursiverIterator 可以对多层结构的迭代器进行迭代,比如遍历一棵树

所有具有层次结构特点的数据都可以用这个接口遍历,如文件夹

关键方法:

hasChildren方法用于判断当前节点是否存在子节点

getChildren方法用于得到当前节点子节点的迭代器

spl中实现该接口的类

RecursiveArrayIterator、RecursiveCachingIterator等以Recursive开头的类都能够进行多层次结构化的遍历

<?php

class MyRecursiveIterator implements RecursiveIterator
{
    private $_data;

    private $_position = 0;

    public function __construct(array $data) {

        $this->_data = $data;

    }

    public function valid() {

        return isset($this->_data[$this->_position]);

    }

    public function hasChildren() {

        return is_array($this->_data[$this->_position]);

    }

    public function next() {

        $this->_position++;

    }

    public function current() {

        return $this->_data[$this->_position];

    }

    public function getChildren() {
        echo '<pre>';
        print_r($this->_data[$this->_position]);
        echo '</pre>';
    }

    public function rewind() {

        $this->_position = 0;

    }

    public function key() {

        return $this->_position;

    }

}

$arr = array(0, 1, 2, 3, 4, 5 => array(10, 20, 30), 6, 7, 8, 9 => array(1, 2, 3));

$mri = new MyRecursiveIterator($arr);

foreach ($mri as $c => $v) {

    if ($mri->hasChildren()) {

        echo "$c has children: <br />";

        $mri->getChildren();

    } else {

        echo "$v <br />";

    }

}

?>

SeekableItertator 可以通过seek方法定位集合里面的某个特定元素

可以通过seek方法定位到集合里面的某个特定元素

seek方法的参数是元素的位置,从0开始计算

spl实现该接口的类

ArrayIterator、DirectoryIterator、FilesystemIterator、GlobIterator、RecursiveArrayIterator、RecursiveDirectoryIterator