Listing 1536
Submitted by Erik Morén, 31 August 2008
/** * A class that uses php built-in interface Iterator. * So you can iterat over a string with a foreach loop. * */ class String extends Element implements Countable, Iterator { /** * Position of the string index * * @var int */ private $current = 0; /** * True if current position is les then length of the string. Otherwise false. * * @var boolean */ private $valid = false; /** * Class constructor. Sets string value an length. * * @param string $html */ function __construct($string) { $this->value['string'] = $string; $this->value['length'] = strlen($string); } /** * Defined by Iterator interface * */ public function rewind(){ $this->current = 0; $this->valid = ($this->current < $this->value['length']); } /** * Defined by Iterator interface * */ public function current(){ return $this->value['string'][$this->current]; } /** * Defined by Iterator interface * * @return string */ public function key(){ return $this->current; } /** * Defined by Iterator interface * */ public function next(){ $this->current++; $this->valid = ($this->current < $this->value['length']); } /** * Defined by Iterator interface * * @return boolean */ public function valid(){ return $this->valid; } /** * Defined by Iterator interface * * @return int */ public function count() { return $this->value['length']; } /** * Reverse one step. * */ public function previous() { if (--$this->current < 0) { $this->current = 0; } } }
