Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/259.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP迭代器-迭代完成时运行函数_Php_Arrays_Oop_Iterator - Fatal编程技术网

PHP迭代器-迭代完成时运行函数

PHP迭代器-迭代完成时运行函数,php,arrays,oop,iterator,Php,Arrays,Oop,Iterator,我有这样一个迭代器: 我想知道如何实现一个在对象完成迭代后运行的方法 例如 foreach($objects as $object){ ... } // here it's finished, and I want to automatically do something 扩展迭代器的示例: class Foo extends ArrayIterator { public function valid() { $result = parent::valid()

我有这样一个迭代器:

我想知道如何实现一个在对象完成迭代后运行的方法

例如

foreach($objects as $object){
  ...
}
// here it's finished, and I want to automatically do something 

扩展迭代器的示例:

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

扩展迭代器以重载
valid()
不是一个好方法,因为您正在向valid()中添加不属于那里的功能。一种较为干净的方法是使用:

class BeforeAndAfterIterator extends RecursiveIteratorIterator
{
    public function beginIteration()
    {
        echo 'begin';
    }
    public function endIteration() 
    {
        echo 'end';
    }
}
然后呢

$it = new BeforeAndAfterIterator(new RecursiveArrayIterator(range(1,10)));
foreach($it as $k => $v) {
    echo "$k => $v";
}
这将给

begin0 => 11 => 22 => 33 => 44 => 55 => 66 => 77 => 88 => 99 => 10end

这两个方法可以重载,因为它们专门用于此目的,并且没有预定义的行为(请注意,我没有调用父方法)。

虽然这样做有效,但这样做是不明智的,因为有效的方法现在有副作用。请参阅我的答案以获得更清晰的方法。@Gordon你是对的。OP应该选择您显示的方法。
begin0 => 11 => 22 => 33 => 44 => 55 => 66 => 77 => 88 => 99 => 10end