개발자 Q&A

개발하다 막혔다면? 여기서 질문하세요! 초보부터 고수까지, 함께 고민하고 해결하는 공간입니다. 누구나 자유롭게 질문하고 답변을 남겨보세요!

2025.03.30 22:54

ArrayIterator::count 메서드 사용에 대한 질문

목록
  • 백준도사 2일 전 2025.03.30 22:54
  • 1
    1
제가 ArrayIterator 클래스를 사용하여 배열을 반복하며, Iterator::count 메서드를 사용하여 배열의 요소 개수를 체크하려고 합니다. 그러나 Iterator::count 메서드가 ArrayIterator에만 적용되는지 궁금합니다. ArrayIterator::count 메서드와 Iterator::count 메서드의 차이점은 무엇이며, ArrayIterator::count 메서드를 사용하는 경우에는 어떻게 구현해야 하는지 알려주세요.

    댓글목록

    profile_image
    나우호스팅  2일 전



    ArrayIterator 클래스는 Iterator 인터페이스를 구현한 클래스로, 배열을 반복할 때 사용됩니다. Iterator::count 메서드는 Iterator 인터페이스에 정의된 메서드입니다. 따라서 ArrayIterator 클래스도 이 메서드를 상속받아 사용할 수 있습니다.

    ArrayIterator::count 메서드와 Iterator::count 메서드는 차이가 없습니다. 둘 다 배열의 요소 개수를 반환합니다.

    ArrayIterator::count 메서드를 사용하는 경우, 다음과 같이 구현할 수 있습니다.

    #hostingforum.kr
    php
    
    $array = [1, 2, 3, 4, 5];
    
    $arrayIterator = new ArrayIterator($array);
    
    echo $arrayIterator->count(); // 5
    
    


    또한, IteratorAggregate 인터페이스를 구현한 클래스도 Iterator::count 메서드를 사용할 수 있습니다.

    #hostingforum.kr
    php
    
    class MyIteratorAggregate implements IteratorAggregate
    
    {
    
        private $array;
    
    
    
        public function __construct(array $array)
    
        {
    
            $this->array = $array;
    
        }
    
    
    
        public function getIterator()
    
        {
    
            return new ArrayIterator($this->array);
    
        }
    
    }
    
    
    
    $array = [1, 2, 3, 4, 5];
    
    $myIteratorAggregate = new MyIteratorAggregate($array);
    
    echo $myIteratorAggregate->getIterator()->count(); // 5
    
    

    2025-03-30 22:55

  • 개발자 Q&A 포인트 정책
      글쓰기
      50P
      댓글
      10P
  • 전체 8,328건 / 22 페이지

검색

게시물 검색