public function __construct() {
$this->position = 0;
}
function rewind() {
var_dump(__METHOD__);
$this->position = 0;
}
function current() {
var_dump(__METHOD__);
return $this->array[$this->position];
}
function key() {
var_dump(__METHOD__);
return $this->position;
}
function next() {
var_dump(__METHOD__);
++$this->position;
}
function valid() {
var_dump(__METHOD__);
return isset($this->array[$this->position]);
}
}
$it = new myIterator;
foreach($it as $key => $value) {
echo '输出键值:';
var_dump($key, $value);
//echo $key;
echo "n";
}
string(16) "myIterator::next"
string(17) "myIterator::valid"
string(19) "myIterator::current"
string(15) "myIterator::key"
输出键值:int(1)
string(14) "second_element"
string(16) "myIterator::next"
string(17) "myIterator::valid"
string(19) "myIterator::current"
string(15) "myIterator::key"
输出键值:int(2)
string(12) "last_element"
string(16) "myIterator::next"
string(17) "myIterator::valid"
public function __construct($array)
{
if (is_array($array)) {
var = $array;
}
}
public function rewind() {
echo "Rewind the first element n";
reset($this->var);
}
public function current() {
$var = current($this->var);
echo "Current element: $varn";
return $var;
}
public function key() {
$var = key($this->var);
echo "The key of the current element: $varn";
return $var;
}
public function next() {
$var = next($this->var);
echo "Move to next element: $varn";
return $var;
}
public function valid() {
$var = $this->current() !== false;
echo "Check validity: {$var}n";
return $var ;
}
}
$values = array(1,2,3);
$it = new MyIterator($values);
foreach ($it as $k => $v) {
print >Program running result:
Key of current element: 1
Key-value pair at this time - - key 1: value 2
Move to next element: 3
Current element: 3
Check validity: 1
Key of current element: 2
Key-value pair at this time - - key 2: value 3
Move to next element:
Current element:
Check validity:
That’s clear now, right?
www.bkjia.com