萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 預定義介面完整解析:Traversable、Iterator、ArrayAccess、Serializable、Closure

六大核心介面

PHP 內建六個基礎介面,構成語言核心行為契約,掌握它們是進階 PHP 開發關鍵。

1. Traversable - 可遍歷標記介面

interface Traversable { }
// 內部介面,不可直接 implements
// 用途:檢測是否可 foreach
if ($obj instanceof Traversable) { foreach ($obj as $k => $v) {} }

實現 Traversable 的類:Iterator、IteratorAggregate、Generator、內建類(ArrayObject、DirectoryIterator 等)

2. Iterator - 迭代器介面

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 結束

3. IteratorAggregate - 聚合迭代器

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

4. ArrayAccess - 陣列式存取

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']);

5. Serializable - 自定義序列化

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 7.4+ 新機制:__serialize / __unserialize

<?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));
    }
}

6. Closure - 閉包類

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"]

最佳實踐

  1. 實現 Iterator 時嚴格遵循五方法契約,valid() 必須可靠
  2. 優先用 IteratorAggregate + ArrayIterator 而非手寫 Iterator
  3. ArrayAccess 配合 Countable 讓對象更像陣列
  4. 序列化敏感數據必須實現 Serializable 或 __serialize
  5. 閉包綁定用於 DSL、構建器、中介軟體模式
  6. PHP 8.1+ 使用 WeakMap 替代強引用集合避免內存洩漏

這六大介面是 PHP 面向對象系統的基石,深度理解能讓你設計出符合語言慣例、高度可組合的 API。

copyright © 萬盛學電腦網 all rights reserved