Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using a method name other than getIterator.
Not returning an iterator object.
✗ Incorrect
The IteratorAggregate interface requires implementing the getIterator() method which returns an iterator.
2fill in blank
mediumComplete 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using interface names instead of a concrete iterator class.
Returning the array directly instead of an iterator.
✗ Incorrect
ArrayIterator is a built-in class that implements Iterator and can iterate over arrays.
3fill in blank
hardFix 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using incorrect method names.
Omitting the return type declaration.
✗ Incorrect
The method must be named getIterator and return a Traversable to satisfy the interface.
4fill in blank
hardFill 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using incorrect return types.
Choosing unrelated class names.
✗ Incorrect
The class name can be any valid name like DataCollection. The getIterator method must return Traversable.
5fill in blank
hardFill 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Mismatching property names.
Incorrect return type for getIterator.
✗ Incorrect
The class name is ItemList, the private property is items, and getIterator returns Traversable.