| 風格 | 程式碼範例 | 優點 | 缺點 |
|---|---|---|---|
| 逐行宣告 (推薦) | $level = 0; // 縮進層級 $size = 0; // 由 tab 決定 | 易於加註解、易閱讀、易維護、版本控制 diff 清楚 | 行數較多 |
| 合併宣告 | $level = 0; $size = 0; 或 $level = $size = 0; | 行數少、緊湊 | 難加個別註解、diff 雜訊大、易忽略型別差異 |
int $foo, $bar[]; // 錯誤:混合標量與陣列<?php
// 型別屬性
class Config {
public int $level = 0;
public int $size = 0;
public array $tags = [];
public ?string $description = null;
}
// 函數參數與回傳型別
function calculate(int $a, int $b): int {
$result = $a + $b; // 區域變數型別推斷
return $result;
}
?>
$a = $b = $c = 0; 連結賦值:難除錯、難加註解、掩蓋型別意圖。function() { $count = 0; if(...) { $count = 0; } } → 易混淆作用域。# PHP_CodeSniffer 規則集 (PSR-12 擴充)
# 禁止合併宣告
"Squiz.Variables.DisallowMultipleAssignments": true
# 強制型別提示
"SlevomatCodingStandard.TypeHints.ParameterTypeHint": true
"SlevomatCodingStandard.TypeHints.ReturnTypeHint": true
# 宣告對齊
"Generic.WhiteSpace.ScopeIndent": true
雖然 PHP 允許彈性宣告,但逐行宣告、明確型別、附加說明註解是團隊協作、長期維護的最佳選擇。配合靜態分析工具(PHPStan/Psalm)與代碼風格檢查(PHP_CodeSniffer),能在提交前攔截風格違規,維持程式碼庫整潔一致。