PHP include语句的行为与正确用法:两种路径生效原因及选型建议
Great question! Let’s unpack why both include paths work in your setup, and which approach is the more reliable,规范 choice.
First, let’s recap your directory structure for clarity:
project/ ├─ index.php └─ lib/ ├─ file1.php └─ file2.php
Why both paths successfully find file2.php
PHP has specific rules for resolving file paths when using include or require, and your two paths trigger different parts of those rules:
When you use
include 'lib/file2.php'infile1.php
This relative path is resolved against the current working directory—which is the directory of the entry script (yourindex.phpinproject/). So PHP looks forproject/lib/file2.php, which exists, hence it works.When you use
include 'file2.php'infile1.php
When you use just a filename without a path prefix, PHP follows this search order:- First, it checks directories listed in PHP’s
include_pathconfig. - If not found there, it checks the directory of the script making the include call (here,
file1.phplives inproject/lib/, so it findsproject/lib/file2.phpimmediately). - If still no luck, it falls back to the current working directory.
- First, it checks directories listed in PHP’s
That’s why both paths end up locating the correct file.
Which写法 is more规范?
The most robust and future-proof approach is to use absolute paths relative to the current script, but let’s break down the options:
Avoid relying on the current working directory: Using
include 'lib/file2.php'depends entirely onindex.phpbeing the entry point and the working directory staying fixed atproject/. If you ever run the script from a different directory (via CLI) or usechdir()elsewhere, this path will break.Using just
include 'file2.php'is better but still risky: While it works here, this relies on PHP’s default search order. If someone adds afile2.phpto a directory ininclude_path, your code might accidentally include the wrong file instead of the one inlib/.The gold standard: Use
__DIR__for absolute path clarity
Forfile1.php, replace your include line with:include __DIR__ . '/file2.php';__DIR__is a magic constant that returns the absolute directory path of the script it’s written in (so forfile1.php, that’s something like/your/absolute/path/project/lib/). Combining it with/file2.phpcreates an unambiguous absolute path to the file. This works no matter what the current working directory is, or howinclude_pathis configured.If you’re stuck on PHP 5.2 or older (which you shouldn’t be, but just in case), use
dirname(__FILE__)instead of__DIR__.
Final takeaway
Both paths work thanks to PHP’s file resolution logic, but they’re not equally reliable. For maintainable, bug-free code, always use absolute paths built with __DIR__ to eliminate any ambiguity about where PHP should look for files.
内容的提问来源于stack exchange,提问作者user3425506




