| 特性 | include | require |
|---|---|---|
| 失敗處理 | 產生 E_WARNING,腳本繼續執行 | 產生 E_COMPILE_ERROR,腳本終止 |
| 使用場景 | 條件載入、模板片段、非關鍵檔案 | 核心類別、設定檔、關鍵依賴 |
| 效能 | 略快(無嚴格檢查) | 略慢(嚴格檢查) |
<?php
// vars.php
$color = 'green';
$fruit = 'apple';
?>
// test.php
echo "A $color $fruit"; // A (變數尚未定義)
include 'vars.php';
echo "A $color $fruit"; // A green apple
?>
被載入檔案繼承 include 所在行的變數範圍。若在函數內 include,則遵循函數區域範圍。
<?php
function foo() {
global $color;
include 'vars.php'; // $color 為全域,$fruit 為區域
echo "A $color $fruit"; // A green apple
}
foo();
echo "A $color $fruit"; // A green ($fruit 不在全域)
?>
載入檔案時,解析器會:
<?php 切回 PHP 模式結論:被載入檔案的 PHP 程式碼必須包裹在 <?php ... ?> 中,否則會直接輸出原始碼。
<?php
// 遠端 PHP 檔案會在遠端執行,本地只拿到輸出結果
include 'https://example.com/file.php?foo=1&bar=2';
// 本地檔案才會繼承變數範圍
$foo = 1; $bar = 2;
include 'file.php'; // 正確
?>
注意:Windows 版 PHP 不支援遠端 include,即使開啟 allow_url_fopen。
<?php
// ❌ 錯誤:語法結構不完整
if ($condition)
include $file;
else
include $other;
// ✅ 正確:語句區塊
if ($condition) {
include $file;
} else {
include $other;
}
?>
<?php
// return.php
$var = 'PHP';
return $var;
// noreturn.php
$var = 'PHP';
// 無 return
// test.php
$foo = include 'return.php'; // $foo = 'PHP'
$bar = include 'noreturn.php'; // $bar = 1 (載入成功回傳 1)
?>
return 終止執行並回傳值$result = include 'file.php'return 時,成功載入回傳 1return,PHP 4+ 支援頂層防止重複載入同一檔案(比較實際路徑,含符號連結解析),適用於類別定義檔。
includerequire,模板/片段用 include__DIR__ . '/config.php' 避免路徑解析歧義@include 抑制警告不推薦,應預先檢查 file_exists 或使用 spl_autoload_register