PHpullh
학습 라이브러리/PHP/IteratorAggregate 구현

PHP · 객체지향

IteratorAggregate 구현

커스텀 컬렉션 객체를 foreach에 자연스럽게 연결하는 예제입니다.

객체지향고급IteratorAggregatecollectioniterable

핵심 설명

커스텀 컬렉션 객체를 foreach에 자연스럽게 연결하는 예제입니다.

PHP code

<?php
class TagCollection implements IteratorAggregate {
    public function __construct(private array $tags) {}

    public function getIterator(): Traversable {
        yield from $this->tags;
    }
}

foreach (new TagCollection(['php', 'api']) as $tag) {
    echo $tag . PHP_EOL;
}

학습 팁

클래스 예제는 생성자, 가시성, 협력 객체의 책임을 함께 보면 실무 감각이 빨리 붙습니다.

주의할 점

가시성, final, readonly 제약을 무시하면 객체 설계가 금방 흐트러집니다.

자주 묻는 질문

IteratorAggregate 구현란 무엇인가요?

커스텀 컬렉션 객체를 foreach에 자연스럽게 연결하는 예제입니다.

IteratorAggregate 구현 학습 시 주의할 점은 무엇인가요?

가시성, final, readonly 제약을 무시하면 객체 설계가 금방 흐트러집니다.