codeisartАвторский веб-архив · 2008–2011

PHP

Создание объектно-ориентированного аналога массива в PHP. Часть 1

В этой статье

Ключи, значения и проверяемый контракт коллекции

Разделяем вставку под явным ключом, добавление в конец и замену. Нулевой ключ не означает отсутствие ключа; сохранённый null не означает отсутствие записи. Эти различия важны для клиентских идентификаторов и необязательных полей.

/**
 * A small array-backed collection for PHP 8.3+.
 * Keys follow PHP array rules: integer 0 and string '0' name the same entry.
 * Explicit keys must be int|string; null is reserved for [] append syntax.
 * Iteration and clone copy the container shallowly; object values stay shared.
 * @implements ArrayAccess<int|string, mixed>
 * @implements IteratorAggregate<int|string, mixed>
 */
class ObjectsArr implements ArrayAccess, Countable, IteratorAggregate
{
    /** @var array<int|string, mixed> */
    private array $items = [];

    protected function validateValue(mixed $value): void
    {
        // Subclasses may enforce a value policy without narrowing public APIs.
    }

    private function checkedKey(mixed $key): int|string
    {
        if (!is_int($key) && !is_string($key)) {
            throw new InvalidArgumentException('Key must be an integer or a string.');
        }
        return $key;
    }

    public function has(mixed $key): bool
    {
        return array_key_exists($this->checkedKey($key), $this->items);