PHP 獨特地同時支援面向過程與面向對象兩種範式,開發者可自由選擇或混合使用。早期版本 (PHP 4 及之前) 以面向過程為主,PHP 5 引入完整物件模型後,OOP 成為主流選擇,但並非絕對優越——面向過程在簡單腳本、快速原型、頁面邏輯直線型處理上仍具開發效率優勢。
| 維度 | 面向過程 | 面向對象 |
|---|---|---|
| 開發週期 | 短、上線快 | 較長、設計前置 |
| 執行效率 | 略高 (無物件開銷) | 略低 (微乎其微) |
| 維護性 | 代碼增長難維護 | 模組化、易擴展、易重構 |
| 團隊協作 | 易衝突、耦合高 | 介面契約、分工明確 |
| 代碼複用 | 函數庫、include | 繼承、組合、Trait、介面 |
| 適用場景 | 小專案、腳本、模板邏輯 | 中大型系統、框架、API、領域模型 |
結論:不爭論誰更好,而是適場景選擇。現代框架 (Laravel、Symfony、ThinkPHP 5+) 皆以 OOP 為核心,掌握 OOP 是進階 PHP 開發者的必修課。
// 每個處理頁面都要寫類似代碼
$email = mysql_real_escape_string($_POST['email']);
$id = (int)$_GET['id'];
if (!preg_match('/^[0-9]+$/', $id)) die('ID 錯誤');
$name = htmlspecialchars(trim($_POST['name']));
// ... 數十個欄位,每個頁面複製貼上,正則不一致、易漏洞
/*** 字串過濾與驗證類 ***/
class StringFilter {
private $maxLength;
public function __construct($maxLength = null) {
$this->maxLength = $maxLength;
}
/** SQL 轉義 (配合 PDO 預處理更佳) */
public function escapeSql($str) {
// 假設已建立 $pdo 連線
global $pdo;
return $pdo->quote($str);
}
/** 僅允許數字 */
public function onlyNumber($str) {
return ctype_digit($str);
}
/** 非空檢查 */
public function notEmpty($str) {
return strlen(trim($str)) > 0;
}
/** 長度檢查 */
public function checkLength($str) {
if ($this->maxLength === null) return true;
return mb_strlen($str, 'UTF-8') <= $this->maxLength;
}
/** XSS 防護輸出 */
public function h($str) {
return htmlspecialchars($str, ENT_QUOTES, 'UTF-8');
}
}
// 使用:實例化一次,到處復用
$filter = new StringFilter(50); // 最大 50 字
// 控制器/處理邏輯變得極度清晰
$email = $filter->escapeSql($_POST['email']);
$isValidId = $filter->onlyNumber($_GET['id']);
$name = $filter->h($_POST['name']); // 輸出時防 XSS
if (!$filter->notEmpty($name)) $errors[] = '姓名不可為空';
資料庫操作類、快取類、第三方 API 客戶端,內部換驅動 (MySQL→PostgreSQL、Redis→Memcached) 不影響呼叫端。
abstract class BaseController {
protected function render($view, $data = []) { /* 通用渲染 */ }
protected function json($data) { /* 統一 JSON 回應 */ }
}
class AdminController extends BaseController {
public function __construct() { $this->auth(); }
protected function auth() { /* 後台權限 */ }
}
class ApiController extends BaseController {
protected function render($view, $data) { /* API 不渲染視圖 */ }
}
class OrderService {
private $paymentGateway;
private $inventory;
// 建構子注入,易測試、易替換實現
public function __construct(PaymentGatewayInterface $payment, InventoryInterface $inventory) {
$this->paymentGateway = $payment;
$this->inventory = $inventory;
}
}
trait Loggable {
protected function log($msg) { /* 寫日誌 */ }
}
class UserService { use Loggable; }
class OrderService { use Loggable; }
declare(strict_types=1); + 型別提示 + 回傳型別readonly 屬性 (PHP 8.1+)PHP OOP 不是為了「面向對象而面向對象」,而是為了管理複雜度。當專案超越單一腳本、需要團隊協作、長期維護、頻繁變更時,OOP 提供的封裝、抽象、多型、DI 等機制,能將系統拆解為低耦合、高內聚的模組,配合現代工具鏈 (Composer、PHPStan、PHPUnit、CI/CD),構建出可靠、可擴展的企業級應用。建議從封裝工具類開始嘗試,逐步引入介面設計與依賴注入,體會 OOP 在實戰中的價值。