0
0
PHPprogramming~30 mins

Iterator interface implementation in PHP - Mini Project: Build & Apply

Choose your learning style9 modes available
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 iterator
Implement all required methods of the Iterator interface: current(), key(), next(), rewind(), and valid()
In the rewind() method, reset $position to 0
In the valid() method, check if the current position is valid in the $fruits array
Use 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
1
Create the FruitCollection class with fruits array
Create a PHP class called FruitCollection with a private array property $fruits containing exactly these fruits: 'Apple', 'Banana', 'Cherry'. Also add a private integer property $position initialized to 0.
PHP
Need a hint?

Define the class and properties exactly as described. Use PHP 7.4+ typed properties.

2
Implement the rewind() and current() methods
Inside the FruitCollection class, implement the rewind() method to reset $position to 0. Also implement the current() method to return the fruit at the current $position.
PHP
Need a hint?

Remember rewind() resets the position. current() returns the item at the current position.

3
Implement key(), next(), and valid() methods
Inside the FruitCollection class, implement the key() method to return the current $position. Implement the next() method to increment $position by 1. Implement the valid() method to check if $position is a valid index in the $fruits array.
PHP
Need a hint?

Use isset() in valid() to check if the position is valid.

4
Create instance and print fruits using foreach
Create an instance of FruitCollection called $fruits. Use a foreach loop to iterate over $fruits and print each fruit on its own line using echo.
PHP
Need a hint?

Use foreach ($fruits as $fruit) and echo $fruit . "\n"; to print each fruit on a new line.