php 为什么在 require_once 中包含 __DIR__?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32444572/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 22:59:20  来源:igfitidea点击:

Why include __DIR__ in the require_once?

phpautoloader

提问by Dan Goodspeed

For example, I always see autoloaders called like this:

例如,我总是看到像这样调用自动加载器:

require_once __DIR__ . '/../vendor/autoload.php';

What is the difference between that and the more concise

那和更简洁有什么区别

require_once '../vendor/autoload.php';

?

?

回答by Evert

PHP scripts run relative to the current path (result of getcwd()), not to the path of their own file. Using __DIR__forces the include to happen relative to their own path.

PHP 脚本相对于当前路径( 的结果getcwd())运行,而不是相对于它们自己文件的路径。使用__DIR__强制包含相对于它们自己的路径发生。

To demonstrate, create the following files (and directories):

为了演示,创建以下文件(和目录):

- file1.php
- dir/
   - file2.php
   - file3.php

If file2.phpincludes file3.phplike this:

如果file2.php包括file3.php这样的:

include `file3.php`.

It will work fine if you call file2.phpdirectly. However, if file1.phpincludesfile2.php, the current directory (getcwd()), will be wrong for file2.php, so file3.phpcannot be included.

如果你file2.php直接打电话,它会工作得很好。但是,如果file1.php包含file2.php,当前目录 ( getcwd()) 将是错误的file2.php,因此file3.php无法包含。

回答by René H?hle

For include its possible to set some folders where PHP search automatically. When you include a file with a relative path you search in all of that folders. Its better to define the real path to prevent some errors in loading wrong files.

对于 include 可以设置一些 PHP 自动搜索的文件夹。当您包含具有相对路径的文件时,您将在所有文件夹中进行搜索。最好定义真实路径,以防止加载错误文件时出现一些错误。

https://secure.php.net/manual/en/function.set-include-path.php

https://secure.php.net/manual/en/function.set-include-path.php

Then you can be sure that you load the correct file.

然后您可以确定您加载了正确的文件。