为什么在 require_once 中包含 __DIR__?
Why include __DIR__ in the require_once?
例如,我总是看到这样调用的自动加载器:
require_once __DIR__ . '/../vendor/autoload.php';
那个和更简洁的有什么区别
require_once '../vendor/autoload.php';
?
为了包括它可以设置一些文件夹,PHP 自动搜索。当您包含一个具有相对路径的文件时,您会在所有这些文件夹中搜索。最好定义真实路径,以防止加载错误文件时出现一些错误。
https://secure.php.net/manual/en/function.set-include-path.php
那么您就可以确定加载了正确的文件。
PHP 脚本 运行 相对于当前路径(getcwd()
的结果),而不是它们自己文件的路径。使用 __DIR__
强制包含相对于它们自己的路径发生。
为了演示,创建以下文件(和目录):
- file1.php
- dir/
- file2.php
- file3.php
如果 file2.php
包括 file3.php
这样的:
include `file3.php`.
直接调用file2.php
就可以了。但是,如果file1.php
includes file2.php
,当前目录(getcwd()
),对于file2.php
来说是错误的,所以file3.php
不能包含。
目前接受的答案没有完全解释使用 __DIR__
的原因,我认为答案是错误的。
我要解释为什么我们真的需要这个。
假设我们有这样的文件结构
- index.php
- file3.php -(content: hello fake world)
- dir/
- file2.php
- file3.php - (content: hello world)
如果我们直接从 file2.php 和 运行 file2.php 中包含 file3.php,我们将看到输出 hello world
。
现在,当我们在 index.php 中包含 file2.php 时,当代码开始执行时,它会再次看到 file2,包括使用 include 'file3.php'
的 file3,首先执行将在当前执行目录中查找 file3 (与 index.php 所在的目录相同)。由于该目录中存在 file3.php,因此它将包含 file3.php
而不是 dir/file3.php
,我们将看到输出 hello fake world
而不是 hello world
.
如果 file3.php 不存在于同一个目录中,它将包含正确的 dir/file3.php
文件,这使得接受的答案无效,因为它声明 file3.php cannot be included
这是不正确的.它包括在内。
然而,这里有使用__DIR__
的必要性。如果我们在 file2.php 中使用 include __DIR__ . '/file3.php'
,那么即使父目录中存在另一个 file3.php,它也会包含正确的文件。
例如,我总是看到这样调用的自动加载器:
require_once __DIR__ . '/../vendor/autoload.php';
那个和更简洁的有什么区别
require_once '../vendor/autoload.php';
?
为了包括它可以设置一些文件夹,PHP 自动搜索。当您包含一个具有相对路径的文件时,您会在所有这些文件夹中搜索。最好定义真实路径,以防止加载错误文件时出现一些错误。
https://secure.php.net/manual/en/function.set-include-path.php
那么您就可以确定加载了正确的文件。
PHP 脚本 运行 相对于当前路径(getcwd()
的结果),而不是它们自己文件的路径。使用 __DIR__
强制包含相对于它们自己的路径发生。
为了演示,创建以下文件(和目录):
- file1.php
- dir/
- file2.php
- file3.php
如果 file2.php
包括 file3.php
这样的:
include `file3.php`.
直接调用file2.php
就可以了。但是,如果file1.php
includes file2.php
,当前目录(getcwd()
),对于file2.php
来说是错误的,所以file3.php
不能包含。
目前接受的答案没有完全解释使用 __DIR__
的原因,我认为答案是错误的。
我要解释为什么我们真的需要这个。
假设我们有这样的文件结构
- index.php
- file3.php -(content: hello fake world)
- dir/
- file2.php
- file3.php - (content: hello world)
如果我们直接从 file2.php 和 运行 file2.php 中包含 file3.php,我们将看到输出 hello world
。
现在,当我们在 index.php 中包含 file2.php 时,当代码开始执行时,它会再次看到 file2,包括使用 include 'file3.php'
的 file3,首先执行将在当前执行目录中查找 file3 (与 index.php 所在的目录相同)。由于该目录中存在 file3.php,因此它将包含 file3.php
而不是 dir/file3.php
,我们将看到输出 hello fake world
而不是 hello world
.
如果 file3.php 不存在于同一个目录中,它将包含正确的 dir/file3.php
文件,这使得接受的答案无效,因为它声明 file3.php cannot be included
这是不正确的.它包括在内。
然而,这里有使用__DIR__
的必要性。如果我们在 file2.php 中使用 include __DIR__ . '/file3.php'
,那么即使父目录中存在另一个 file3.php,它也会包含正确的文件。