1.SPL 是什么?
SPL:standard php library php标准库,此 从php5.0起开始内置的组件和接口,在5.3之后逐渐成熟。由于内置在php5开发环境中,无需任何配置。
根据官方定义,“a collection of interfaces and classes that are meant to solve standard problems.”
然而在目前的使用者,spl更多地被看作是一种使object模仿的array行为的interfaces和classes。
SPL对PHP引擎进行了扩展,例如ArrayAccess、Countable和SeekableIterator等接口,它们用于以数组形式操做对象。同时还可使用RecursiveIterator,ArrayObjects等其余迭代器进行数组的迭代操做。
他还内置了几个对象,例如Exceptions,SplObserver,spltorage以及splautoloadregister,splclasses,iteratorapply等的帮助函数,用于重载对应的功能。
2.Iterator
spl的核心概念是Iterator,这指一种设计模式(Design Pattern),"provide an object which traverses some aggregate structure,abstracting away assumptions about the implementation of that structure."
通俗的说,Iterator可以使许多不一样的数据结构,都能有统一的操做界面,好比一个数据库的结果集、同一目录的文件集或者一个文本中每一行构成的集合。
SPL规定,全部部署了Iterator界面的class,均可以用在foreach loop中。Iterator界面包含如下必须部署的五个方法:php
current()数据库
This method returns the current index's value. You are solely
responsible for tracking what the current index is as the
interface does not do this for you.设计模式
key()数组
This method returns the value of the current index's key. For
foreach loops this is extremely important so that the key
value can be populated.数据结构
next()app
This method moves the internal index forward one entry.less
rewind()ide
This method should reset the internal index to the first element.函数
valid()oop
This method should return true or false if there is a current
element. It is called after rewind() or next().
ArrayAccess界面
部署ArrayAccess界面,可使object像Array那样操做,可是必须包含四个必须部署的方法
ArrayObject类
此类将Array转换为Object
ArrayIterator类
这个类其实是对ArrayObject类的补充,为后者提供遍历功能。也支持offset类方法和count()方法
RecursiveArrayIterator类和RecursiveIteratorIterator类
ArrayIterator类和ArrayObject类,只支持遍历一维数组,若是要遍历多维数组,必须先用RecursiveIteratorIterator生成一个Iterator,而后再对这个Iterator使用RecursiveIteratorIterator
FilterIterator
FilterIterator类能够对元素进行过滤,只要在accept()方法中设置过滤条件就能够了。
SimpleXMLIterator类这个类用来遍历xml文件CachingIterator类这个类有一个hasNext()方法,用来判断是否还有下一个元素LimitIterator类这个类用来限定返回结果集的数量和位置,必须提供offset和limit两个参数,与SQL命令中的limit语句相似SplFileObject类这个类用来对文本文件进行遍历