在PHP中有好几个预定义的接口,比较常用的四个接口(IteratorAggregate(聚合式aggregate迭代器Iterator)、Countable、ArrayAccess、Iterator)分别给大家详细介绍下。
IteratorAggregate(聚合式aggregate迭代器Iterator)接口
代码如下:
IteratorAggregate extends Traversable {
abstract public Traversable getIterator(void)
}
这个接口实现了一个功能——创建外部迭代器,具体怎么理解呢,当我们使用foreach对对象进行便遍历的时候,如果没有继承IteratorAggregate接口,遍历的是对象中所有的public属性(只能是public $var这种形式)。要是继承了IteratorAggregate,会使用类中实现的getIterator方法返回的对象,这里要注意返回的一定要是一个Traversable对象或者扩展自Traversable的对象,否则会抛出异常
//看个例子class My{ private $_data = [ 'a' => '燕睿涛', 'b' => 'yanruitao', 'c' => 'LULU', ]; public function getIterator() { return new ArrayIterator($this->_data); }}$obj = new My;foreach ($obj as $key => $value) { echo "$key => $value/n";}//输出结果为空 class My implements IteratorAggregate { private $_data = [ 'a' => '燕睿涛', 'b' => 'yanruitao', 'c' => 'LULU', ]; public function getIterator() { return new ArrayIterator($this->_data); }}$obj = new My;foreach ($obj as $key => $value) { echo "$key => $value/n";}//结果:a => 燕睿涛b => yanruitaoc => LULU
Countable接口
代码如下:
Countable {
abstract public int count(void)
}
这个接口用于统计对象的数量,具体怎么理解呢,当我们对一个对象调用count的时候,如果函数没有继承Countable将一直返回1,如果继承了Countable会返回所实现的count方法所返回的数字,看看下面的例子:
class CountMe{ protected $_myCount = 3; public function count() { return $this->_myCount; } } $countable = new CountMe(); echo count($countable);//返回1class CountMe implements Countable{ protected $_myCount = 3; public function count() { return $this->_myCount; } } $countable = new CountMe(); echo count($countable); //返回3ArrayAccess接口ArrayAccess { abstract public boolean offsetExists(mixed $offset) abstract public mixed offsetGet(mixed $offset) public void offsetSet(mixed $offset, mixed $value) public void offsetUnset(mixed $offset)}class CountMe{ protected $_myCount = 3; public function count() { return $this->_myCount; } } $countable = new CountMe(); echo count($countable);//返回1class CountMe implements Countable{ protected $_myCount = 3; public function count() { return $this->_myCount; } } $countable = new CountMe(); echo count($countable); //返回3
ArrayAccess接口
代码如下:
新闻热点
疑难解答