php-src/ext/spl/examples/cachingiterator.inc

81 lines
1.4 KiB
PHP
Raw Normal View History

2003-11-18 22:18:38 +00:00
<?php
2003-12-08 08:31:08 +00:00
define('CIT_CALL_TOSTRING', 1);
define('CIT_CATCH_GET_CHILD', 2);
2003-11-18 22:18:38 +00:00
class CachingIterator
{
protected $it;
protected $current;
protected $key;
protected $more;
2003-12-06 19:03:17 +00:00
protected $strValue;
protected $getStrVal;
2003-11-18 22:18:38 +00:00
2003-12-08 08:31:08 +00:00
function __construct(Iterator $it, $flags = CIT_CALL_TOSTRING)
2003-11-22 20:51:15 +00:00
{
2003-11-18 22:18:38 +00:00
$this->it = $it;
2003-12-08 08:31:08 +00:00
$this->flags = $flags & (CIT_CALL_TOSTRING|CIT_CATCH_GET_CHILD);
2003-11-18 22:18:38 +00:00
}
2003-11-22 20:51:15 +00:00
function rewind()
{
2003-11-18 22:18:38 +00:00
$this->it->rewind();
$this->next();
}
2003-11-22 20:51:15 +00:00
function next()
{
if ($this->more = $this->it->valid()) {
2003-11-18 22:18:38 +00:00
$this->current = $this->it->current();
$this->key = $this->it->key();
2003-12-08 08:31:08 +00:00
if ($this->flags & CIT_CALL_TOSTRING) {
2003-12-06 19:03:17 +00:00
if (is_object($this->current)) {
$this->strValue = $this->current->__toString();
} else {
$this->strValue = (string)$this->current;
}
2003-12-04 20:56:32 +00:00
}
2003-11-18 22:18:38 +00:00
} else {
$this->current = NULL;
$this->key = NULL;
$this->strValue = NULL;
2003-11-18 22:18:38 +00:00
}
$this->it->next();
}
function valid()
2003-11-22 20:51:15 +00:00
{
2003-11-18 22:18:38 +00:00
return $this->more;
}
2003-11-22 20:51:15 +00:00
function hasNext()
{
return $this->it->valid();
2003-11-18 22:18:38 +00:00
}
2003-11-22 20:51:15 +00:00
function current()
{
2003-11-18 22:18:38 +00:00
return $this->current;
}
2003-11-22 20:51:15 +00:00
function key()
{
2003-11-18 22:18:38 +00:00
return $this->key;
}
2003-11-22 20:51:15 +00:00
function __call($func, $params)
{
2003-11-18 22:18:38 +00:00
return call_user_func_array(array($this->it, $func), $params);
}
2003-11-22 20:51:15 +00:00
function __toString()
{
2003-12-08 08:31:08 +00:00
if (!$this->flags & CIT_CALL_TOSTRING) {
2003-12-06 19:03:17 +00:00
throw new exception('CachingIterator does not fetch string value (see CachingIterator::__construct)');
}
return $this->strValue;
2003-11-18 22:18:38 +00:00
}
}
?>