SPL之Iterator(迭代器)接口
作者:互联网
前言:SPL是用于解决典型问题(standard problems)的一组接口与类的集合。
<?php /** * Class MyIterator * 在 PHP 中,通常情况下遍历数组使用 foreach 来遍历。 * Iterator 接口,只要实现了这个接口,对象就可以通过 foreach 来迭代 * foreach对象时,依次调用: * rewind() 重置到第一个元素 * valid() 检查当前位置是否有效 * current() 返回当前元素 * key() 返回当前元素的键 * next() 指向下一个元素 */ class MyIterator implements Iterator { private $arr; private $position; public function __construct(Array $arr) { $this->arr = $arr; $this->position = 0; } // 3、返回当前值 public function current() { // TODO: Implement current() method. var_dump(__METHOD__); return $this->arr[$this->position]; } // 5、把数组指针往下移 public function next() { // TODO: Implement next() method. var_dump(__METHOD__); ++$this->position; } // 4、返回当前值的下标, 返回键名 public function key() { // TODO: Implement key() method. var_dump(__METHOD__); return $this->position; } // 2、验证下标的值是否存在,存在则继续往下走 返回布尔值 public function valid() { // TODO: Implement valid() method. var_dump(__METHOD__); return isset($this->arr[$this->position]); } // 1、重置数组的指针 public function rewind() { // TODO: Implement rewind() method. var_dump(__METHOD__); } } $data = ['tom', 18, 'man']; $my = new MyIterator($data); echo '<pre>'; foreach ($my as $k => $v){ echo '<b>'.$k. ' => '.$v. '</b> '; }
运行:
string(18) "MyIterator::rewind" string(17) "MyIterator::valid" string(19) "MyIterator::current" string(15) "MyIterator::key" 0 => tom string(16) "MyIterator::next" string(17) "MyIterator::valid" string(19) "MyIterator::current" string(15) "MyIterator::key" 1 => 18 string(16) "MyIterator::next" string(17) "MyIterator::valid" string(19) "MyIterator::current" string(15) "MyIterator::key" 2 => man string(16) "MyIterator::next" string(17) "MyIterator::valid"
标签:__,Iterator,迭代,MyIterator,next,valid,SPL,dump,string 来源: https://www.cnblogs.com/cshaptx4869/p/10415514.html