
RecursiveDirectoryIterator::rewind() 메서드는 현재 위치를 처음으로 되돌립니다. 하지만, 이 메서드는 디렉토리나 파일의 방문 순서를 다시 시작하지 않습니다.
이 메서드는 디렉토리나 파일의 방문 순서를 기억하지 않기 때문에, 이전에 방문한 디렉토리나 파일을 다시 방문할 수 있습니다.
해당 메서드를 사용하려면, hasNext() 메서드를 호출한 후, rewind() 메서드를 호출해야 합니다.
하지만, rewind() 메서드를 호출한 후, hasNext() 메서드를 호출하면, 이전에 방문한 디렉토리나 파일이 다시 방문될 수 있습니다.
이 문제를 해결하려면, IteratorAggregate 인터페이스를 구현한 클래스를 사용하거나, RecursiveDirectoryIterator를 직접 구현하는 방법이 있습니다.
IteratorAggregate 인터페이스를 구현한 클래스를 사용하는 방법은 다음과 같습니다.
#hostingforum.kr
php
class MyDirectoryIterator implements IteratorAggregate
{
private $iterator;
public function __construct($directory)
{
$this->iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($directory));
}
public function getIterator()
{
return $this->iterator;
}
}
RecursiveDirectoryIterator를 직접 구현하는 방법은 다음과 같습니다.
#hostingforum.kr
php
class MyRecursiveDirectoryIterator extends RecursiveIteratorIterator
{
private $currentDirectory;
public function __construct($directory)
{
parent::__construct(new RecursiveDirectoryIterator($directory));
$this->currentDirectory = null;
}
public function rewind()
{
parent::rewind();
$this->currentDirectory = null;
}
public function current()
{
if ($this->currentDirectory === null) {
$this->currentDirectory = parent::current();
}
return $this->currentDirectory;
}
}
이러한 방법을 사용하면, 이전에 방문한 디렉토리나 파일을 다시 방문하지 않도록 할 수 있습니다.
2025-07-14 18:48