Iterator interface implementation
📖 Scenario: You are creating a simple collection class in PHP that holds a list of fruits. You want to make this class iterable so you can loop through the fruits easily.
🎯 Goal: Build a PHP class called FruitCollection that implements the Iterator interface to allow looping over the fruits.
📋 What You'll Learn
Create a class called
FruitCollection with a private array property $fruits containing exactly these fruits: 'Apple', 'Banana', 'Cherry'Add a private integer property
$position to track the current position in the iteratorImplement all required methods of the
Iterator interface: current(), key(), next(), rewind(), and valid()In the
rewind() method, reset $position to 0In the
valid() method, check if the current position is valid in the $fruits arrayUse a
foreach loop to iterate over an instance of FruitCollection and print each fruit💡 Why This Matters
🌍 Real World
Custom iterable classes are useful when you want to create your own collections or data structures that behave like arrays but have extra features.
💼 Career
Understanding how to implement Iterator is important for PHP developers working with custom data containers, frameworks, or libraries that require iterable objects.
Progress0 / 4 steps