SyntaxStudy
Sign Up
PHP PHP Standard Library Interfaces
PHP Advanced 6 min read

PHP Standard Library Interfaces

SPL Interfaces

PHP's Standard Library includes built-in interfaces: Countable, Iterator, ArrayAccess, Stringable, and others for integration with built-in language features.

Example
<?php
class Collection implements Countable, ArrayAccess, Iterator {
    private array $items = [];
    private int $position = 0;

    // Countable
    public function count(): int { return count($this->items); }

    // ArrayAccess
    public function offsetExists(mixed $offset): bool { return isset($this->items[$offset]); }
    public function offsetGet(mixed $offset): mixed { return $this->items[$offset]; }
    public function offsetSet(mixed $offset, mixed $value): void {
        $offset === null ? $this->items[] = $value : $this->items[$offset] = $value;
    }
    public function offsetUnset(mixed $offset): void { unset($this->items[$offset]); }

    // Iterator
    public function current(): mixed { return $this->items[$this->position]; }
    public function key(): int { return $this->position; }
    public function next(): void { $this->position++; }
    public function rewind(): void { $this->position = 0; }
    public function valid(): bool { return isset($this->items[$this->position]); }
}

$col = new Collection();
$col[] = "a";
$col[] = "b";
echo count($col);      // 2
foreach ($col as $item) { echo $item; } // ab
Pro Tip

Implementing ArrayAccess makes your objects usable with array syntax ($obj[$key]) natively.