檔案包含是 PHP 程式碼模組化、重用的基礎機制。include、require 及其 _once 變體,在錯誤處理、重複包含防護上有關鍵差異。本文完整對比四種函數並提供實務建議。
| 函數 | 找不到檔案 | 腳本執行 | 重複包含 | 回傳值 | 效能 |
|---|---|---|---|---|---|
include |
Warning(警告) | 繼續執行 | 允許重複 | 成功 1,失敗 false | 略快 |
require |
Fatal Error(致命錯誤) | 立即停止 | 允許重複 | 無(成功不回傳) | 略快 |
include_once |
Warning | 繼續執行 | 忽略重複 | 成功 1,失敗 false | 稍慢(需檢查) |
require_once |
Fatal Error | 立即停止 | 忽略重複 | 無 | 稍慢 |
<?php
include 'missing.php';
echo "Hello World!"; // 仍會執行
?>
// Warning: include(missing.php): Failed to open stream...
// Warning: include(): Failed opening 'missing.php'...
// Hello World!
<?php
require 'missing.php';
echo "Hello World!"; // 不會執行
?>
// Warning: require(missing.php): Failed to open stream...
// Fatal error: require(): Failed opening required 'missing.php'...
// 腳本終止
<?php
// views/layout/header.php
?>
<!DOCTYPE html>
<html lang="zh-TW">
<head>
<meta charset="UTF-8">
<title><?= $pageTitle ?? 'My Site' ?></title>
</head>
<body>
<header>
<nav><a href="/">首頁</a> | <a href="/about">關於</a></nav>
</header>
<main>
<?php
// views/layout/footer.php
?>
</main>
<footer>© 2024 My Site</footer>
</body>
</html>
<?php
// index.php
$pageTitle = '首頁';
include __DIR__ . '/views/layout/header.php';
?>
<h1>歡迎來到首頁</h1>
<p>內容...</p>
<?php
include __DIR__ . '/views/layout/footer.php';
?>
<?php
// config/app.php
return [
'app' => [
'name' => 'My App',
'env' => 'production',
'debug' => false,
'url' => 'https://example.com',
],
'db' => [
'driver' => 'mysql',
'host' => '127.0.0.1',
'port' => 3306,
'database' => 'myapp',
'username' => 'db_user',
'password' => 'secret',
'charset' => 'utf8mb4',
],
];
?>
<?php
// 使用
$config = require __DIR__ . '/config/app.php'; // 取得陣列
$pdo = new PDO(
"{$config['db']['driver']}:host={$config['db']['host']};dbname={$config['db']['database']};charset={$config['db']['charset']}",
$config['db']['username'],
$config['db']['password']
);
?>
<?php
// helpers.php
function h(string $str): string {
return htmlspecialchars($str, ENT_QUOTES, 'UTF-8');
}
function url(string $path = ''): string {
return rtrim($_ENV['APP_URL'] ?? '', '/') . '/' . ltrim($path, '/');
}
function dd(mixed $value): never {
var_dump($value);
exit;
}
?>
<?php
require_once __DIR__ . '/helpers.php'; // 全域函數庫用 once 防重複定義錯誤
echo h('<script>alert(1)</script>');
?>
/var/www/html/config.php、C:\xampp\htdocs\config.phpphp.ini 設定的搜尋路徑列表// index.php
include 'config.php'; // 正確
// admin/index.php
include 'config.php'; // 錯誤!尋找 admin/config.php
include '../config.php'; // 正確但脆弱
include __DIR__ . '/../config.php'; // ✅ 最佳:相對於當前檔案位置
require_once:設定檔、核心類別、自動載入器、資料庫連線include:header、footer、sidebar(缺失不應中斷整頁)require_once:防止重複定義致命錯誤__DIR__ 建立絕對路徑require 'vendor/autoload.php' 後無需手動 include 類別檔return [...],類別檔只定義類別<?php
// Laravel Blade 模板繼承
// layouts/app.blade.php
@yield('content')
// pages/home.blade.php
@extends('layouts.app')
@section('content')
<h1>首頁</h1>
@endsection
// Symfony Twig
// base.html.twig
{% block body %}{% endblock %}
// index.html.twig
{% extends 'base.html.twig' %}
{% block body %}
<h1>首頁</h1>
{% endblock %}
src/ 目錄對應命名空間,逐步移除手動 require。模板建議採用 Plates(原生 PHP 模板引擎)或 Twig(功能完整),分離邏輯與視圖。