PHP 內建六個基礎介面,構成語言核心行為契約,掌握它們是進階 PHP 開發關鍵。
interface Traversable { }
// 內部介面,不可直接 implements
// 用途:檢測是否可 foreach
if ($obj instanceof Traversable) { foreach ($obj as $k => $v) {} }
實現 Traversable 的類:Iterator、IteratorAggregate、Generator、內建類(ArrayObject、DirectoryIterator 等)
interface Iterator extends Traversable {
public function current(); // 當前元素值
public function key(); // 當前鍵名
public function next(): void; // 移至下一個
public function rewind(): void; // 重置到第一個
public function valid(): bool; // 當前位置是否有效
}
<?php
class NumberRange implements Iterator {
private $start, $end, $current;
public function __construct($start, $end) {
$this->start = $start;
$this->end = $end;
}
public function rewind() { $this->current = $this->start; }
public function current() { return $this->current; }
public function key() { return $this->current - $this->start; }
public function next() { $this->current++; }
public function valid() { return $this->current <= $this->end; }
}
foreach (new NumberRange(1, 5) as $k => $v) {
echo "$k => $v\n"; // 0=>1, 1=>2, 2=>3, 3=>4, 4=>5
}
rewind() → valid() → current()/key() → next() → valid() → ... → valid()=false 結束
interface IteratorAggregate extends Traversable {
public function getIterator(): Traversable;
}
委派給外部迭代器,適合包裝陣列、資源、其他可遍歷對象。
<?php
class DataCollection implements IteratorAggregate {
private $data = array();
public function add($item) { $this->data[] = $item; }
public function getIterator() {
return new ArrayIterator($this->data); // 內建陣列迭代器
}
}
$coll = new DataCollection();
$coll->add('a'); $coll->add('b');
foreach ($coll as $item) { echo "$item "; } // a b
interface ArrayAccess {
public function offsetExists($offset): bool;
public function offsetGet($offset): mixed;
public function offsetSet($offset, $value): void;
public function offsetUnset($offset): void;
}
<?php
class Config implements ArrayAccess {
private $data = array();
public function __construct(array $config) { $this->data = $config; }
public function offsetExists($offset) { return isset($this->data[$offset]); }
public function offsetGet($offset) { return $this->data[$offset] ?? null; }
public function offsetSet($offset, $value) {
if (is_null($offset)) $this->data[] = $value;
else $this->data[$offset] = $value;
}
public function offsetUnset($offset) { unset($this->data[$offset]); }
// 額外便利方法
public function get($key, $default = null) { return $this->data[$key] ?? $default; }
public function all() { return $this->data; }
}
$config = new Config(['app' => ['debug' => true]]);
echo $config['app']['debug'] ? 'on' : 'off'; // on
$config['new_key'] = 'value';
unset($config['app']);
interface Serializable {
public function serialize(): string;
public function unserialize($data): void;
}
替代 __sleep/__wakeup,完全控制序列化格式。
<?php
class UserData implements Serializable {
private $id, $name, $password, $token; // 敏感欄位不序列化
public function __construct($id, $name, $password) {
$this->id = $id; $this->name = $name; $this->password = $password;
$this->token = bin2hex(random_bytes(16));
}
public function serialize() {
return serialize(array(
'id' => $this->id,
'name' => $this->name,
// password, token 故意略過
));
}
public function unserialize($data) {
$arr = unserialize($data);
$this->id = $arr['id'];
$this->name = $arr['name'];
$this->password = null; // 重新登入獲取
$this->token = bin2hex(random_bytes(16));
}
}
<?php
class ModernUserData {
// ...
public function __serialize(): array {
return ['id' => $this->id, 'name' => $this->name];
}
public function __unserialize(array $data): void {
$this->id = $data['id'];
$this->name = $data['name'];
$this->password = null;
$this->token = bin2hex(random_bytes(16));
}
}
Closure 類代表匿名函數,提供綁定、呼叫、反射功能。
<?php
$greet = function($name) { return "Hello $name"; };
// 綁定 $this 與作用域
class Greeter { private $prefix = 'Hi'; }
$bound = $greet->bindTo(new Greeter(), 'Greeter');
// $bound 現在在 Greeter 作用域,可訪問私有屬性
// 靜態閉包 (PHP 5.4+):無 $this 綁定,較輕量
$static = static function($x) { return $x * 2; };
// Closure::call() 臨時綁定 (PHP 7+)
class Math { private $factor = 10; }
$math = new Math();
$multiply = function($x) { return $x * $this->factor; };
echo $multiply->call($math, 5); // 50
// 反射閉包
$rf = new ReflectionFunction($greet);
echo $rf->getFileName() . ':' . $rf->getStartLine();
Traversable (內部) ├── Iterator ├── IteratorAggregate └── Generator (內部實現) ArrayAccess (獨立) Serializable (獨立) Closure (類,非介面)
<?php
class Collection implements IteratorAggregate, ArrayAccess, Countable, Serializable {
private $items = array();
public function add($item) { $this->items[] = $item; }
public function getIterator() { return new ArrayIterator($this->items); }
public function count() { return count($this->items); }
// ArrayAccess
public function offsetExists($o) { return isset($this->items[$o]); }
public function offsetGet($o) { return $this->items[$o] ?? null; }
public function offsetSet($o, $v) { is_null($o) ? $this->items[] = $v : $this->items[$o] = $v; }
public function offsetUnset($o) { unset($this->items[$o]); }
// Serializable
public function serialize() { return serialize($this->items); }
public function unserialize($d) { $this->items = unserialize($d); }
}
$c = new Collection();
$c->add('a'); $c->add('b');
$c[2] = 'c';
foreach ($c as $v) echo "$v "; // a b c
echo json_encode($c); // ["a","b","c"]
Iterator 時嚴格遵循五方法契約,valid() 必須可靠IteratorAggregate + ArrayIterator 而非手寫 IteratorArrayAccess 配合 Countable 讓對象更像陣列Serializable 或 __serializeWeakMap 替代強引用集合避免內存洩漏這六大介面是 PHP 面向對象系統的基石,深度理解能讓你設計出符合語言慣例、高度可組合的 API。