Skip to content

PHP Include

include 和 require 语句允许您将一个 PHP 文件的内容插入到另一个文件中。这对于跨多个页面重用代码非常有用,例如头部、底部、配置设置或函数库。

当一个文件被包含时,PHP 会有效地暂停当前脚本的执行,处理被包含的文件,然后恢复执行原脚本。

include 和 require 都实现了相同的基本目标,但它们在处理指定文件找不到或无法读取的错误时有所不同:

  • require: 如果找不到文件,require 会产生一个致命的 E_COMPILE_ERROR 级别错误,立即终止脚本执行。对于您的应用程序无法正常运行所必需的文件(例如,数据库连接、核心配置、必需的类定义),请使用 require。
  • include: 如果找不到文件,include 会产生一个非致命的 E_WARNING 级别错误,并且脚本会尝试继续执行(尽管如果缺少被包含文件的内容,可能会出现问题)。对于可选文件或当您希望脚本即使缺少一部分内容也能尝试继续执行时,请使用 include(例如,包含一个可能并非总是存在的模板片段)。

一般建议:在现代 PHP 开发中,特别是在构建结构化应用程序时,通常优先使用 require(或 require_once)来引入关键依赖项,以确保如果缺少必要部分,应用程序能快速失败 (fail fast),从而防止后续出现意外行为。

PHP 还提供了 include_once 和 require_once。这些语句的行为与其对应的语句(include 和 require)相同,但增加了一个检查:它们确保在脚本执行期间,指定的文件只包含一次。如果该文件已被包含,则后续对同一文件的 include_once 或 require_once 调用将被忽略。

这对于防止由于重复包含同一个文件而可能导致的函数、类或常量重复定义错误至关重要。

最佳实践:对于包含定义(如函数或类)的文件,使用 require_once 以防止重复声明错误。如果包含是可选的,但仍应只发生一次,则使用 include_once。

include ‘path/to/filename.php’; include_once ‘path/to/filename.php’;

require ‘path/to/filename.php’; require_once ‘path/to/filename.php’;

// Parentheses are optional but sometimes used // require_once(‘path/to/filename.php’);

文件路径可以是相对路径或绝对路径。PHP 会检查 include_path 配置指令来解析相对路径。

创建一个名为 footer.php 的文件:

Copyright © 2000- My Awesome Website. All rights reserved.

将此底部文件包含到您的主页 (index.php) 中:

<!-- index.php -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Welcome!</title>
</head>
<body>
<h1>Welcome to my home page!</h1>
<p>Some content goes here.</p>
<p>More content.</p>
<?php include 'footer.php'; // 或者使用 include_once ?>
</body>
</html>

创建一个配置文件 config.php(这里使用 require_once 更安全):

在另一个脚本中使用该配置:

<?php
// db_connect.php
require_once 'config.php'; // 必需 - 脚本需要这些常量
echo "Connecting to database host: " . DATABASE_HOST . "<br>";
if (DEBUG_MODE) {
echo "Debug mode is ON.<br>";
} else {
echo "Debug mode is OFF.<br>";
}
// ... proceed with database connection using constants ...
?>

使用 include 包含一个不存在的文件:

<?php
// script_using_include.php
echo "<h1>Welcome!</h1>";
include 'non_existent_file.php'; // 将会生成警告
echo "<p>This line might still be executed, despite the warning.</p>";
?>

使用 require 包含一个不存在的文件:

<?php
// script_using_require.php
echo "<h1>Welcome!</h1>";
require 'non_existent_file.php'; // 将会生成致命错误
// 这行代码将不会被执行,因为脚本会终止。
echo "<p>This line will never be reached.</p>";
?>

现代替代方案:自动加载 (Autoloading)

Section titled “现代替代方案:自动加载 (Autoloading)”

虽然 require_once 对于过程式代码或引导启动仍然必不可少,但现代 PHP 应用程序严重依赖于自动加载 (autoloading),特别是对于面向对象编程。自动加载在首次使用类文件时自动包含它们,从而无需编写冗长的 require_once 列表。

Composer 等工具管理依赖项并设置符合 PSR-4 标准的自动加载器,这是当代 PHP 开发中的标准做法。理解 require/include 是基础,但请注意,自动加载是大型项目中管理类依赖项的首选方法。