라이브러리

[PHP] ParentIterator::accept - 수용 가능성 결정




ParentIterator::accept

PHP 8.1 버전부터 ParentIterator 클래스가 추가되었습니다. ParentIterator는 IteratorAggregate 인터페이스를 구현한 클래스의 부모 클래스를 나타내는 Iterator를 반환합니다.

ParentIterator::accept 메소드는 IteratorAggregate 인터페이스를 구현한 클래스의 부모 클래스의 Iterator를 반환합니다.

예제

#hostingforum.kr
php

class ParentIteratorExample implements IteratorAggregate {

    private $children;



    public function __construct() {

        $this->children = [

            new ChildIteratorExample('Child 1'),

            new ChildIteratorExample('Child 2'),

            new ChildIteratorExample('Child 3'),

        ];

    }



    public function getIterator() {

        return new ParentIterator($this->children);

    }

}



class ChildIteratorExample implements IteratorAggregate {

    private $name;



    public function __construct($name) {

        $this->name = $name;

    }



    public function getIterator() {

        return new ArrayIterator($this->name);

    }

}



$parentIterator = new ParentIteratorExample();

$parentIterator->getIterator();



foreach ($parentIterator as $child) {

    echo $child->current() . "
";

}



위의 예제에서, ParentIteratorExample 클래스는 IteratorAggregate 인터페이스를 구현하고, ChildIteratorExample 클래스는 IteratorAggregate 인터페이스를 구현합니다. ParentIteratorExample 클래스의 getIterator 메소드는 ParentIterator 인스턴스를 반환합니다. ChildIteratorExample 클래스의 getIterator 메소드는 ArrayIterator 인스턴스를 반환합니다.

ParentIterator 인스턴스를 사용하여, ChildIteratorExample 인스턴스의 Iterator를 접근할 수 있습니다.

accept 메소드 사용

#hostingforum.kr
php

class ParentIteratorExample implements IteratorAggregate {

    private $children;



    public function __construct() {

        $this->children = [

            new ChildIteratorExample('Child 1'),

            new ChildIteratorExample('Child 2'),

            new ChildIteratorExample('Child 3'),

        ];

    }



    public function getIterator() {

        return new ParentIterator($this->children);

    }

}



class ChildIteratorExample implements IteratorAggregate {

    private $name;



    public function __construct($name) {

        $this->name = $name;

    }



    public function getIterator() {

        return new ArrayIterator($this->name);

    }

}



$parentIterator = new ParentIteratorExample();

$parentIterator->getIterator();



$parentIterator->accept(function (ParentIterator $iterator) {

    foreach ($iterator as $child) {

        echo $child->current() . "
";

    }

});



위의 예제에서, accept 메소드를 사용하여, ParentIterator 인스턴스에 콜백 함수를 전달합니다. 콜백 함수는 ParentIterator 인스턴스의 Iterator를 접근할 수 있습니다.

결론

ParentIterator::accept 메소드는 IteratorAggregate 인터페이스를 구현한 클래스의 부모 클래스의 Iterator를 반환합니다. accept 메소드를 사용하여, IteratorAggregate 인터페이스를 구현한 클래스의 Iterator를 접근할 수 있습니다.

이 예제는 ParentIterator::accept 메소드의 사용 방법을 보여주고, IteratorAggregate 인터페이스를 구현한 클래스의 Iterator를 접근하는 방법을 보여줍니다.
  • profile_image
    나우호스팅 @pcs8404 

    호스팅포럼 화이팅!

    댓글목록

    등록된 댓글이 없습니다.

  • 전체 10,077건 / 345 페이지

검색

게시물 검색