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