為何要實作陣列介面?
- 統一存取介面:
$obj['key']、foreach ($obj as $k => $v)、isset($obj['key'])、count($obj)
- 封裝資料來源:資料庫、API、檔案、快取,對外統一陣列語法
- 延遲載入:存取時才從資料庫查詢
- 型別安全:IDE 自動完成、靜態分析支援
核心介面定義
// ArrayAccess:陣列式存取
interface ArrayAccess {
public function offsetExists(mixed $offset): bool;
public function offsetGet(mixed $offset): mixed;
public function offsetSet(mixed $offset, mixed $value): void;
public function offsetUnset(mixed $offset): void;
}
// Iterator:foreach 遍歷
interface Iterator extends Traversable {
public function current(): mixed;
public function next(): void;
public function key(): mixed;
public function valid(): bool;
public function rewind(): void;
}
// Countable:count()
interface Countable {
public function count(): int;
}
// Serializable:序列化控制 (PHP 7.4+ 建議用 __serialize/__unserialize)
interface Serializable {
public function serialize(): string;
public function unserialize(string $data): void;
}
完整實作範例:設定管理器
<?php
class Config implements ArrayAccess, Iterator, Countable {
private array $data = [];
private int $position = 0;
public function __construct(array $initial = []) {
$this->data = $initial;
}
// ArrayAccess
public function offsetExists(mixed $offset): bool {
return array_key_exists($offset, $this->data);
}
public function offsetGet(mixed $offset): mixed {
return $this->data[$offset] ?? null;
}
public function offsetSet(mixed $offset, mixed $value): void {
if (is_null($offset)) {
$this->data[] = $value;
} else {
$this->data[$offset] = $value;
}
}
public function offsetUnset(mixed $offset): void {
unset($this->data[$offset]);
}
// Iterator
public function rewind(): void { $this->position = 0; }
public function current(): mixed { return $this->data[$this->position] ?? null; }
public function key(): mixed { return array_keys($this->data)[$this->position] ?? null; }
public function next(): void { $this->position++; }
public function valid(): bool { return isset($this->data[array_keys($this->data)[$this->position] ?? null]); }
// Countable
public function count(): int { return count($this->data); }
// 額外:轉陣列
public function toArray(): array { return $this->data; }
}
// 使用
$config = new Config(['app_name' => 'MyApp', 'debug' => true]);
echo $config['app_name']; // MyApp
$config['version'] = '1.0'; // 設定
isset($config['debug']); // true
unset($config['debug']); // 刪除
foreach ($config as $k => $v) { // 遍歷
echo "$k = $v\n";
}
echo count($config); // 2
進階:延遲載入資料庫記錄
class DbCollection implements ArrayAccess, Iterator, Countable {
private PDO $pdo;
private string $table;
private array $cache = [];
private array $keys = [];
private int $pos = 0;
public function __construct(PDO $pdo, string $table) {
$this->pdo = $pdo;
$this->table = $table;
$this->loadKeys();
}
private function loadKeys(): void {
$this->keys = $this->pdo->query("SELECT id FROM {$this->table}")->fetchAll(PDO::FETCH_COLUMN);
}
public function offsetExists(mixed $offset): bool {
return in_array($offset, $this->keys, true);
}
public function offsetGet(mixed $offset): mixed {
if (!isset($this->cache[$offset])) {
$stmt = $this->pdo->prepare("SELECT * FROM {$this->table} WHERE id = ?");
$stmt->execute([$offset]);
$this->cache[$offset] = $stmt->fetch() ?: null;
}
return $this->cache[$offset];
}
public function offsetSet(mixed $offset, mixed $value): void { throw new Exception('Read-only'); }
public function offsetUnset(mixed $offset): void { throw new Exception('Read-only'); }
public function rewind(): void { $this->pos = 0; }
public function current(): mixed { return $this->offsetGet($this->keys[$this->pos] ?? null); }
public function key(): mixed { return $this->keys[$this->pos] ?? null; }
public function next(): void { $this->pos++; }
public function valid(): bool { return isset($this->keys[$this->pos]); }
public function count(): int { return count($this->keys); }
}
注意事項
- 實作
Countable 才能讓 count($obj) 生效。
Iterator 為單向游標,並發遍歷會互相干擾;需支援多重遍歷請實作 IteratorAggregate 回傳新 ArrayIterator。
ArrayAccess 的 offsetSet(null, $val) 對應 $obj[] = $val。
- PHP 8.1+ 可用
ArrayObject 繼承快速實作,但自訂類別更彈性。