test-01/Collection.php

51 lines
1.0 KiB
PHP

<?php
class Collection implements Iterator {
private int $cursor = 0;
public function __construct(
private array $items = []
) {}
#[ReturnTypeWillChange]
public function current(): int
{
return $this->items[$this->cursor];
}
#[ReturnTypeWillChange]
public function key(): int
{
return $this->cursor;
}
#[ReturnTypeWillChange]
public function next(): void
{
++$this->cursor;
}
#[ReturnTypeWillChange]
public function prev(): int {
--$this->cursor;
}
public function rewind(): void {
$this->cursor = 0;
}
public function valid(): bool
{
return isset($this->items[$this->cursor]);
}
}
// Adding an array [1,2,3,4,5,6,7,8,9,10] to the collection
$collection = new Collection([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
// Calculating the sum of the elements in the collection
$sum = 0;
foreach ($collection as $item) {
$sum += $item;
}
echo "The sum of the elements in the collection is: $sum\n";