0
0
PHPprogramming~20 mins

IteratorAggregate interface in PHP - Mini Project: Build & Apply

Choose your learning style9 modes available
Using the IteratorAggregate Interface in PHP
📖 Scenario: You are creating a simple collection class in PHP that holds a list of book titles. You want to make this collection easy to loop over using a foreach loop.
🎯 Goal: Build a PHP class called BookCollection that implements the IteratorAggregate interface to allow looping over the books.
📋 What You'll Learn
Create a class named BookCollection with a private array property called books.
Add a constructor to BookCollection that accepts an array of book titles and assigns it to books.
Implement the getIterator() method from the IteratorAggregate interface to return an ArrayIterator of the books array.
Create an instance of BookCollection with exactly these books: '1984', 'Brave New World', 'Fahrenheit 451'.
Use a foreach loop to print each book title on its own line.
💡 Why This Matters
🌍 Real World
Custom collection classes are common in PHP applications to group related data and make it easy to loop over them.
💼 Career
Understanding IteratorAggregate helps you write clean, reusable code and work with PHP libraries that expect iterable objects.
Progress0 / 4 steps
1
Create the BookCollection class with books property
Create a PHP class called BookCollection with a private property books initialized as an empty array.
PHP
Need a hint?

Use private array $books = []; inside the class.

2
Add constructor to accept books array
Add a constructor method __construct to BookCollection that takes an array parameter $books and assigns it to the private property $books.
PHP
Need a hint?

Constructor should accept array $books and assign it to $this->books.

3
Implement IteratorAggregate interface and getIterator method
Make BookCollection implement the IteratorAggregate interface. Add the method getIterator() that returns a new ArrayIterator of the $books property.
PHP
Need a hint?

Remember to add implements IteratorAggregate after the class name.

4
Create instance and loop to print books
Create a BookCollection instance named $collection with the books '1984', 'Brave New World', and 'Fahrenheit 451'. Use a foreach loop to print each book title on its own line.
PHP
Need a hint?

Use foreach ($collection as $book) and echo $book . "\n"; inside the loop.