優雅、可維護的 PHP 代碼不是靠運氣,而是源於日積月累的良好習慣。本文分享前兩個能顯著提升代碼質量的核心實踐。
統一的代碼風格能降低團隊協作的認知負擔。PSR-12 規範了縮進(4 空格)、命名規範、控制結構格式等細節。
<?php
declare(strict_types=1);
namespace App\Service;
class OrderProcessor
{
public function calculateTotal(array $items): float
{
$total = 0.0;
foreach ($items as $item) {
$total += $item['price'] * $item['quantity'];
}
return round($total, 2);
}
}
實踐建議:在專案中引入 PHP_CodeSniffer(phpcs)並配置 pre-commit hook,強制提交前自動檢查風格。
PHP 7+ 引入的標量類型聲明與 declare(strict_types=1) 能在編寫階段攔截大量型別錯誤。
<?php
declare(strict_types=1);
function calculateDiscount(float $price, int $percentage): float
{
if ($percentage < 0 || $percentage > 100) {
throw new InvalidArgumentException('折扣百分比必須在 0-100 之間');
}
return round($price * (1 - $percentage / 100), 2);
}
優勢:IDE 靜態分析更精準、重構更安全、文檔屬性自我說明,減少運行時意外。
這兩個習慣是現代 PHP 專業開發的基石。下篇將介紹「依賴注入與容器化」、「單元測試驅動開發」以及「持續重構與代碼審查」三大進階實踐。