0
0
PHPprogramming~10 mins

IteratorAggregate interface in PHP - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to implement the IteratorAggregate interface in the class.

PHP
<?php
class MyCollection implements IteratorAggregate {
    private array $items = [];

    public function __construct(array $items) {
        $this->items = $items;
    }

    public function [1]() {
        return new ArrayIterator($this->items);
    }
}
?>
Drag options to blanks, or click blank then click option'
AgetItems
BfetchIterator
CgetIterator
Diterator
Attempts:
3 left
💡 Hint
Common Mistakes
Using a method name other than getIterator.
Not returning an iterator object.
2fill in blank
medium

Complete the code to return an iterator over the items array.

PHP
<?php
public function getIterator() {
    return new [1]($this->items);
}
?>
Drag options to blanks, or click blank then click option'
ATraversable
BIteratorAggregate
CIterator
DArrayIterator
Attempts:
3 left
💡 Hint
Common Mistakes
Using interface names instead of a concrete iterator class.
Returning the array directly instead of an iterator.
3fill in blank
hard

Fix the error in the method signature to properly implement IteratorAggregate.

PHP
<?php
class Collection implements IteratorAggregate {
    public function [1](): Traversable {
        // method body
    }
}
?>
Drag options to blanks, or click blank then click option'
AgetIterator
Biterator
CgetItems
DfetchIterator
Attempts:
3 left
💡 Hint
Common Mistakes
Using incorrect method names.
Omitting the return type declaration.
4fill in blank
hard

Fill both blanks to create a class that implements IteratorAggregate and returns an iterator over a private array.

PHP
<?php
class [1] implements IteratorAggregate {
    private array $data;

    public function __construct(array $data) {
        $this->data = $data;
    }

    public function getIterator(): [2] {
        return new ArrayIterator($this->data);
    }
}
?>
Drag options to blanks, or click blank then click option'
ADataCollection
BTraversable
CIterator
DArrayAccess
Attempts:
3 left
💡 Hint
Common Mistakes
Using incorrect return types.
Choosing unrelated class names.
5fill in blank
hard

Fill all three blanks to create a class that implements IteratorAggregate, stores items, and returns an iterator.

PHP
<?php
class [1] implements IteratorAggregate {
    private array $[2];

    public function __construct(array $items) {
        $this->[2] = $items;
    }

    public function getIterator(): [3] {
        return new ArrayIterator($this->[2]);
    }
}
?>
Drag options to blanks, or click blank then click option'
AItemList
Bitems
CTraversable
Ddata
Attempts:
3 left
💡 Hint
Common Mistakes
Mismatching property names.
Incorrect return type for getIterator.