PHP 7.1 引入**短陣列語法 `[]` 進行解構賦值**,取代冗長的 `list()`,並支援**鍵值指定**、**巢狀結構**,大幅提升程式碼可讀性與彈性。本文完整說明語法、實務範例、進階技巧與未來提案展望。
<?php
// PHP 5/7.0 list()
$values = ['foo', 'bar'];
list($v1, $v2) = $values;
// PHP 7.1 短語法 []
[$v1, $v2] = ['foo', 'bar']; // 相同效果,更簡潔
不再依賴陣列順序,直接對應鍵名:
$data = ['name' => 'Alice', 'age' => 30, 'city' => 'Taipei'];
// 傳統 list() 無法指定鍵,需按順序
list($name, $age, $city) = array_values($data); // 易錯、需維持順序
// PHP 7.1+ 指定鍵值
['name' => $name, 'age' => $age, 'city' => $city] = $data;
// 甚至可只取需要的鍵
['age' => $age, 'city' => $city] = $data; // $name 不會被定義
$users = [
['id' => 1, 'name' => 'Alice', 'email' => 'alice@example.com'],
['id' => 2, 'name' => 'Bob', 'email' => 'bob@example.com'],
];
// PHP 7.0 僅支援數值索引
foreach ($users as list($id, $name, $email)) { ... }
// PHP 7.1+ 指定鍵值,順序無關、可跳過欄位
foreach ($users as ['id' => $id, 'email' => $email]) {
echo "ID: $id, Email: $email\n";
}
$matrix = [[1, 2], [3, 4]];
[[$a, $b], [$c, $d]] = $matrix;
// $a=1, $b=2, $c=3, $d=4
// 結合鍵值
$records = [
['user' => ['id' => 1, 'name' => 'A'], 'meta' => ['role' => 'admin']],
['user' => ['id' => 2, 'name' => 'B'], 'meta' => ['role' => 'user']],
];
foreach ($records as ['user' => ['id' => $id, 'name' => $name], 'meta' => ['role' => $role]]) {
echo "$id - $name ($role)\n";
}
| 場景 | 範例 |
|---|---|
| 函式多值回傳 | function getUser() { return ['id' => 1, 'name' => 'A']; }
['id' => $id, 'name' => $name] = getUser(); |
| API 回應解析 | $json = json_decode($response, true); ['data' => ['items' => $items], 'meta' => ['total' => $total]] = $json; |
| 設定檔映射 | ['database' => ['host' => $host, 'port' => $port]] = $config; |
| 物件屬性快速賦值 | class User { public $name, $email; }
$user = new User();
['name' => $user->name, 'email' => $user->email] = $input; |
社群討論中更激進的提案:
<?php
// 建構子直接解構帶型別提示 (假想語法)
class User {
public function __construct(
['name' => string $name, 'email' => string $email, 'age' => int $age]
) {
$this->name = $name;
$this->email = $email;
$this->age = $age;
}
}
$user = new User(['email' => 'a@b.com', 'name' => 'Alice', 'age' => 25]);
// 順序無關、有型別檢查、IDE 完美提示
若成真,PHP 將擁有類似 **Python `**kwargs` / Ruby 關鍵字參數** 的能力,參數順序完全解耦,極大提升 API 設計彈性。
| 功能 | PHP 5.6 | PHP 7.0 | PHP 7.1+ |
|---|---|---|---|
| `list($a, $b) = [...]` | ✅ | ✅ | ✅ |
| `[$a, $b] = [...]` | ❌ | ❌ | ✅ |
| `['key' => $var] = [...]` | ❌ | ❌ | ✅ |
| `foreach ($arr as ['k' => $v])` | ❌ | ❌ | ✅ |
| 巢狀解構 `[[$a], [$b]]` | ❌ | ❌ | ✅ |