PHP iterator - run function when iteration completes
I have a iterator like this one:
http://nz.php.net/manual/en/class.iterator.php
And I was wondering how could I implement a method that runs when the objects have finished iterating.
For eg
foreach($objects a开发者_运维知识库s $object){
...
}
// here it's finished, and I want to automatically do something
Example for extending an Iterator:
class Foo extends ArrayIterator
{
public function valid() {
$result = parent::valid();
if (!$result) {
echo 'after';
}
return $result;
}
}
$x = new Foo(array(1, 2, 3));
echo 'before';
foreach ($x as $y) {
echo $y;
}
// output: before123after
Extending an iterator to overload valid()
is not a good approach because you are adding functionality into valid() that doesnt belong there. A somewhat cleaner approach would be to use:
class BeforeAndAfterIterator extends RecursiveIteratorIterator
{
public function beginIteration()
{
echo 'begin';
}
public function endIteration()
{
echo 'end';
}
}
and then do
$it = new BeforeAndAfterIterator(new RecursiveArrayIterator(range(1,10)));
foreach($it as $k => $v) {
echo "$k => $v";
}
which would then give
begin0 => 11 => 22 => 33 => 44 => 55 => 66 => 77 => 88 => 99 => 10end
Those two methods are okay to overload because they are specifically for that purpose and have no predefined behavior (mind that I'm not calling the parent method).
function valid(){
$isValid=...;
if(!$isValid)
doStuff();
return $isValid;
}
精彩评论