| 特性 | include | require |
|---|---|---|
| 檔案不存在 | 發出 Warning,腳本繼續執行 | 發出 Fatal Error,腳本終止 |
| 解析時機 | **執行時** 遇到該行才編譯載入 | **編譯期** 即載入 (PHP 4) / 執行前載入 (PHP 5+) |
| 條件載入 | 支援 if (...) include 'a.php'; | 無條件載入,即使在 if(false) 區塊 |
| 效能 | 略慢 (執行時決定) | 略快 (預先編譯) |
| 回傳值 | 可接收被載入檔案的 return 值 | 同 |
現代建議 (PHP 5.3+):幾乎永遠用 require_once。自動載入器 (PSR-4/Composer) 已取代手動 include/require,唯有「條件載入不同模板」等極少數場景仍用 include。
project/
├── public/ # 公開入口 (index.php, assets/)
├── src/
│ ├── Core/ # 核心基礎類 (Config, Database, Router, Container)
│ ├── Domain/ # 業務領域模型 (Entity, Repository Interface, Service)
│ │ ├── User/
│ │ ├── Product/
│ │ └── Order/
│ ├── Infrastructure/ # 基礎設施實作 (PDO Repository, Redis Cache, Mailer)
│ └── Presentation/ # 呈現層 (Controller, View, Middleware, FormRequest)
├── templates/ # Blade/Twig/Smarty 模板
├── tests/ # 單元/整合測試
├── vendor/ # Composer 依賴
├── composer.json
└── .env
<?php
// layout.php - 統一版面
$title = $title ?? 'My Site';
$content = $content ?? '';
?>
<!DOCTYPE html>
<html>
<head>
<title><?= htmlspecialchars($title) ?></title>
<link rel="stylesheet" href="/css/app.css">
</head>
<body>
<header><?php include 'partials/nav.php'; ?></header>
<main><?= $content ?></main>
<footer><?php include 'partials/footer.php'; ?></footer>
</body>
</html>
<?php
// article.php - 內容頁
require_once __DIR__ . '/bootstrap.php'; // 載入自動載入、DB、Session
$article = $articleRepository->findBySlug($_GET['slug'] ?? '');
if (!$article) { http_response_code(404); include '404.php'; exit; }
$title = $article->title;
ob_start();
include 'templates/article_detail.php';
$content = ob_get_clean();
include 'layout.php';
// composer.json
{
"autoload": {
"psr-4": {
"App\\": "src/"
}
}
}
// 執行 composer dump-autoload
// 之後直接 use App\Domain\User\UserService; 即可使用,零 require。
模組化不是把檔案切碎,而是**依業務邊界劃分邏輯單元**,配合 Composer 自動載入、依賴注入容器、介面導向程式設計,構建高內聚、低耦合、可測試、可擴展的系統。從 include 'config.php' 開始,走向 use App\Core\Config;,是每個 PHP 開發者必經的架構演進之路。