四函數對比表
| 函數 | 找不到文件 | 語法錯誤 | 重複包含 | 返回值 | 典型用途 |
| include | Warning + 繼續 | Warning + 繼續 | 每次執行 | 1/false | 模板、可選配置 |
| include_once | Warning + 繼續 | Warning + 繼續 | 只執行一次 | 1/false | 函數庫、類定義 |
| require | Fatal Error 停止 | Fatal Error 停止 | 每次執行 | 1/不返回 | 核心依賴、初始化 |
| require_once | Fatal Error 停止 | Fatal Error 停止 | 只執行一次 | 1/不返回 | 核心類庫、單例註冊 |
性能考量
_once 版本需維護已包含文件表(EG(included_files)),極微量開銷,可忽略。
- OpCache 啟用後,編譯結果緩存,二次包含幾乎零成本。
- 條件包含:
if ($cond) include 'a.php'; 只能用 include,require 編譯期必須存在。
最佳實踐
- **類/介面/函數定義**:
require_once(核心)或 Composer 自動加載(現代標準)。
- **配置文件**:
require_once(缺失即致命)。
- **視圖模板**:
include(允許不存在時降級)。
- **動態路由加載**:
include 配合 file_exists 判斷。
- **廢棄
include/require 變量傳遞**:改用函數參數、返回值、依賴注入。
自動加載替代方案
<?php
// Composer PSR-4
require __DIR__.'/vendor/autoload.php';
// 手動最小實現
spl_autoload_register(function($class) {
$file = __DIR__.'/src/'.str_replace('\\','/',$class).'.php';
if (file_exists($file)) require $file;
});