| 特性 | include | require |
|---|---|---|
| 檔案不存在 | 發出 Warning (E_WARNING),腳本繼續執行 | 發出 Fatal Error (E_COMPILE_ERROR),腳本立即停止 |
| 返回值 | 成功返回 1,失敗返回 false | 成功返回 1,失敗不返回(腳本已終止) |
| 適用場景 | 非必要檔案(模板片段、廣告、側邊欄) | 核心必要檔案(設定檔、核心類別、函數庫) |
<?php // include 範例 include 'header.php'; // 相對路徑 include '/absolute/path/config.php'; $var = include 'config.php'; // 可接收被包含檔案的 return 值 // require 範例 require 'database.php'; // 核心設定,失敗必須停止 require_once 'functions.php'; // 只載入一次
// ✅ 推薦:定義專案根目錄常數
define('ROOT_PATH', __DIR__ . '/../');
require ROOT_PATH . 'config/database.php';
// ❌ 不推薦:相對路徑需解析
require '../../config/database.php';
<?php
// Composer 自動載入(現代標準)
require_once __DIR__ . '/vendor/autoload.php';
// 手動實作 PSR-4 自動載入
spl_autoload_register(function ($class) {
$prefix = 'App\\';
$base_dir = __DIR__ . '/src/';
$len = strlen($prefix);
if (strncmp($class, $prefix, $len) !== 0) return;
$relative_class = substr($class, $len);
$file = $base_dir . str_replace('\\', '/', $relative_class) . '.php';
if (file_exists($file)) {
require $file;
}
});
<?php
// ❌ 差:無論條件皆載入
require 'heavy_library.php';
if ($need_feature) { use_feature(); }
// ✅ 好:條件式載入
if ($need_feature) {
require 'heavy_library.php';
use_feature();
}
// ✅ 更好:自動載入讓類別首次使用時才載入
<?php
// config/app.php
return [
'app_name' => 'MyApp',
'debug' => true,
'database' => [
'host' => 'localhost',
'name' => 'myapp',
],
];
// 使用
$config = require 'config/app.php'; // 接收返回的陣列
echo $config['app_name'];
<?php
// 錯誤:路徑拼接錯誤
require 'config' . '/database.php'; // 易寫錯
// 正確:使用常數或 __DIR__
require __DIR__ . '/config/database.php';
// 錯誤:被包含檔案有輸出導致 header 失效
// config.php
// ❌ 多餘輸出
// 正確:被包含檔案不應有輸出
// ✅
`require`/`include` **不影響**命名空間。被包含檔案內的程式碼繼承當前命名空間,除非檔案內部宣告 `namespace`。
<?php
// main.php
namespace App;
require 'helper.php'; // helper.php 內程式碼也在 App 命名空間
// helper.php
function helper_func() {} // 實際為 App\helper_func
// 若 helper.php 要定義全域函數:
namespace {
function global_helper() {}
}