Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 as $object){
  ...
}
// here it's finished, and I want to automatically do something 
like image 605
Anny Avatar asked Aug 04 '11 14:08

Anny


1 Answers

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
like image 193
Yoshi Avatar answered Sep 20 '22 04:09

Yoshi