bhylu.com

Advertisements

PHP Iterable Objects

An object can provide an iterable interface while keeping its internal representation private. Callers then depend on traversal rather than a public mutable array.

How it works

IteratorAggregate supplies a Traversable from getIterator. The implementation can return an ArrayIterator for a small stored list or a generator for lazy values. State whether repeated traversal is supported and whether returned objects are shared or copied. An iterable interface alone does not make the underlying data immutable or turn each traversal into a database snapshot.

Run it locally

Run this complete source locally with PHP 8.2 or newer. Save it using the filename shown and run the command below. PHP is not currently available in Bhylu’s browser playground. Apache and MySQL are not needed for an ordinary CLI example.

php -l iterable-objects.php
php iterable-objects.php

Download this source as a local PHP lab file. Keep lab files separate from the Bhylu project and production data.

Example

PHP 8.2+ · iterable-objects.php

<?php
declare(strict_types=1);

class ItemNames implements IteratorAggregate {
    public function __construct(private array $names) {}
    public function getIterator(): Traversable { return new ArrayIterator($this->names); }
}
$names = new ItemNames(["Spade", "Drill"]);
foreach ($names as $name) echo $name, "\n";

Expected result

Spade
Drill

The caller sees two names through foreach without directly editing the private storage property. The ArrayIterator provides the traversal protocol for this small fixture. If the elements were mutable objects, they could still be shared; protecting the container reference is not a deep-copy policy.

Check the official PHP manual for detailed version and API contracts.