라이브러리
[PHP] FilterIterator::rewind - 반복자를 되감기
FilterIterator::rewind
`FilterIterator`는 PHP의 SPL (Standard PHP Library) 중 하나로, 다른 이터레이터에서 필터링을 수행하는 데 사용됩니다. `FilterIterator`의 `rewind` 메서드는 현재 이터레이터의 위치를 처음으로 되돌립니다.
# 사용법
`rewind` 메서드는 이터레이터의 현재 위치를 처음으로 되돌립니다. 이터레이터의 위치는 `current` 메서드나 `next` 메서드를 호출할 때마다 이동됩니다.
# 예제
#hostingforum.kr
php
// 예제 1: FilterIterator::rewind 사용하기
$numbers = new ArrayIterator([1, 2, 3, 4, 5]);
$evenFilter = new CallbackFilterIterator($numbers, function($value) {
return $value % 2 == 0;
});
// 이터레이터의 위치를 처음으로 되돌립니다.
$evenFilter->rewind();
// 이터레이터의 현재 위치를 출력합니다.
echo current($evenFilter) . "
"; // 2
// 이터레이터의 위치를 다음으로 이동합니다.
$evenFilter->next();
// 이터레이터의 현재 위치를 출력합니다.
echo current($evenFilter) . "
"; // 4
# 예제 2: FilterIterator::rewind 사용하기 (파일 이터레이터)
#hostingforum.kr
php
// 예제 2: FilterIterator::rewind 사용하기 (파일 이터레이터)
$files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator('example'));
$txtFilter = new CallbackFilterIterator($files, function($file) {
return $file->isFile() && $file->getExtension() == 'txt';
});
// 이터레이터의 위치를 처음으로 되돌립니다.
$txtFilter->rewind();
// 이터레이터의 현재 위치를 출력합니다.
echo $txtFilter->current()->getPathname() . "
"; // example/example.txt
// 이터레이터의 위치를 다음으로 이동합니다.
$txtFilter->next();
// 이터레이터의 현재 위치를 출력합니다.
echo $txtFilter->current()->getPathname() . "
"; // example/example2.txt
# 예제 3: FilterIterator::rewind 사용하기 (데이터베이스 이터레이터)
#hostingforum.kr
php
// 예제 3: FilterIterator::rewind 사용하기 (데이터베이스 이터레이터)
$pdo = new PDO('sqlite:example.db');
$stmt = $pdo->query('SELECT * FROM users');
$usersFilter = new CallbackFilterIterator($stmt, function($row) {
return $row['age'] > 18;
});
// 이터레이터의 위치를 처음으로 되돌립니다.
$usersFilter->rewind();
// 이터레이터의 현재 위치를 출력합니다.
echo $usersFilter->current()['name'] . "
"; // John
// 이터레이터의 위치를 다음으로 이동합니다.
$usersFilter->next();
// 이터레이터의 현재 위치를 출력합니다.
echo $usersFilter->current()['name'] . "
"; // Alice
# 결론
`FilterIterator::rewind` 메서드는 이터레이터의 현재 위치를 처음으로 되돌립니다. 이터레이터의 위치는 `current` 메서드나 `next` 메서드를 호출할 때마다 이동됩니다. 이 메서드는 파일 이터레이터, 데이터베이스 이터레이터, 그리고 일반 이터레이터에서 사용할 수 있습니다.
-
- 나우호스팅 @pcs8404
-
호스팅포럼 화이팅!
댓글목록
등록된 댓글이 없습니다.