include 和 require 都会把另一个 PHP 文件的内容导入(并执行)到当前文件中。唯一的区别在于它们如何处理失败:如果文件缺失,require 会引发致命错误(fatal error),而 include 只会发出一条警告(warning)并继续执行。
include "config.php"; // if missing → WARNING, script CONTINUES
require "database.php"; // if missing → FATAL ERROR, script STOPS
include → file missing → emits a Warning, execution continues (file's code skipped)
require → file missing → throws a Fatal Error, execution HALTS
对于应用程序缺了就无法运行的文件(核心类、关键配置、数据库初始化),使用 require —— 你希望在它们缺失时直接强制停止。对于可选文件(例如侧边栏模板),缺失不应让整个页面崩溃,则使用 include。
require_once "functions.php"; // include the file ONLY if not already included
include_once "helper.php";
require_once/include_once 只在文件尚未被包含时才导入它 —— 当某个文件可能被多次包含时(例如一个被多个文件引入的类定义),这对于避免 “cannot redeclare function/class” 错误是至关重要的。
// included files share the SAME scope and can define functions, classes, variables
// config.php:
$dbHost = "localhost";
// main.php:
require "config.php";
echo $dbHost; // "localhost" — the variable is available
// ❌ old style — manually requiring every class file
require_once "User.php";
require_once "Order.php";
// ✅ modern — Composer AUTOLOADING loads classes on demand automatically
require "vendor/autoload.php"; // one line; classes load when used (PSR-4)
$user = new User(); // User.php loaded automatically
在现代 PHP 中,你很少再为类手动使用 require —— Composer 的自动加载器会按需加载它们。你只需用 require "vendor/autoload.php" 引导一次即可。
理解 include 与 require 是 PHP 的基础但重要的知识 —— 它们是 PHP 文件之间共享代码的方式,而二者的区别对正确性很关键。
关键点在于失败时的行为:对必需文件使用 require(这样在关键文件缺失时应用会快速且明确地失败),对可选文件使用 include(这样一个缺失的非关键文件不会让页面崩溃)。
了解 _once 变体在实践中几乎是必备的,可以防止因不小心两次包含某个类或函数定义而产生的常见 “cannot redeclare” 错误。
同样重要的是理解现代背景:虽然这些结构是基础性的,但现代 PHP 依赖 Composer 自动加载(按需加载类),而不是手动 require 每个文件,因此在当前的代码中,你大多只需 require "vendor/autoload.php" 一次,剩下的交给自动加载处理。
既懂 include/require 的机制(以及何时该用哪种失败模式),又懂现代自动加载如何取代手动包含,是处理新旧 PHP 代码库的日常知识。