
RecursiveIteratorIterator::rewind 메서드를 호출하면 디렉토리 트리의 모든 요소를 다시 반복문으로 순회하게 되는 이유는 RecursiveIteratorIterator 클래스의 내부 로직 때문입니다.
RecursiveIteratorIterator 클래스는 RecursiveIterator 인터페이스를 구현한 클래스입니다. RecursiveIterator 인터페이스는 rewind() 메서드를 구현해야 하며, 이 메서드는 현재 위치를 저장하고 다시 시작할 때 저장된 위치로 이동하는 기능을 제공합니다.
그러나 RecursiveIteratorIterator 클래스는 RecursiveIterator 인터페이스를 구현하지 않고, Iterator 인터페이스를 구현한 클래스입니다. Iterator 인터페이스는 rewind() 메서드를 구현하지 않습니다.
따라서 RecursiveIteratorIterator::rewind 메서드를 호출하면 디렉토리 트리의 모든 요소를 다시 반복문으로 순회하게 됩니다.
디렉토리 트리의 현재 위치를 저장하고, 다시 시작할 때 저장된 위치로 이동하는 방법은 다음과 같습니다.
1. RecursiveIteratorIterator 클래스의 rewind() 메서드를 오버라이딩하여 현재 위치를 저장하고 다시 시작할 때 저장된 위치로 이동하는 기능을 구현합니다.
2. RecursiveIteratorIterator 클래스의 rewind() 메서드를 호출하기 전에, 현재 위치를 저장하는 메서드를 호출합니다.
3. RecursiveIteratorIterator 클래스의 rewind() 메서드를 호출한 후, 저장된 위치로 이동하는 메서드를 호출합니다.
예제 코드는 다음과 같습니다.
#hostingforum.kr
php
class MyRecursiveIteratorIterator extends RecursiveIteratorIterator {
private $currentPosition;
public function rewind() {
parent::rewind();
$this->currentPosition = $this->getInnerIterator()->key();
}
public function getCurrentPosition() {
return $this->currentPosition;
}
public function seek($position) {
$this->getInnerIterator()->seek($position);
$this->currentPosition = $position;
}
}
$iterator = new MyRecursiveIteratorIterator(new RecursiveDirectoryIterator('/path/to/directory'));
foreach ($iterator as $file) {
// ...
}
// 현재 위치를 저장합니다.
$currentPosition = $iterator->getCurrentPosition();
// 다시 시작할 때 저장된 위치로 이동합니다.
$iterator->seek($currentPosition);
이 예제 코드에서는 MyRecursiveIteratorIterator 클래스를 정의하여 RecursiveIteratorIterator 클래스의 rewind() 메서드를 오버라이딩합니다. MyRecursiveIteratorIterator 클래스는 현재 위치를 저장하고 다시 시작할 때 저장된 위치로 이동하는 기능을 제공합니다.
2025-06-05 05:48