使用 php __DIR__
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18035049/
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
using php __DIR__
提问by Jeff
I'm trying to create a config.php file that defines a global variable which contains the path to a directory called "projectfiles". The idea is that any file can point to this directory regardless of where it is in the file tree.
我正在尝试创建一个 config.php 文件,该文件定义了一个全局变量,该变量包含一个名为“projectfiles”的目录的路径。这个想法是任何文件都可以指向这个目录,而不管它在文件树中的什么位置。
Can I use __DIR__
for this? Would someone be willing to give me an example of how this might work? I was thinking of something like the following:
我可以用__DIR__
这个吗?有人愿意给我一个例子来说明这可能是如何工作的吗?我在想类似以下的事情:
I want to define an directory here: in the /config.php
file
我想在这里定义一个目录:在/config.php
文件中
$projectfiles = __DIR__("projectfiles/")
Then I want a library file to be able to use this variable in /venders/library/generalfunctions.php
file
然后我想要一个库文件能够在/venders/library/generalfunctions.php
文件中使用这个变量
include("../../../config.php");
$file = $projectfiles/testfile.php
Suggestions?
建议?
回答by Garet Claborn
__DIR__
is certainly what you are looking for. Use it to provide relative paths for required files. I would highly suggest using require_once
or include_once
for all library files.
__DIR__
肯定是你要找的。使用它来提供所需文件的相对路径。我强烈建议对所有库文件使用require_once
或include_once
。
if( !defined( __DIR__ ) ) define( __DIR__, dirname(__FILE__) );
require_once( __DIR__ . '/../../../config.php');
.
.
.
// you code here
Using the first line ensures you wont run into trouble with PHP 5.2 and back. This will allow you to include files based on directory structure instead of relative to the script called. Many frameworks use dirname(__FILE__)
instead, but it is rather wasteful to run more than once. It is better to just add it somewhere with a check.
使用第一行可确保您在使用 PHP 5.2 及后面版本时不会遇到麻烦。这将允许您根据目录结构而不是相对于调用的脚本来包含文件。很多框架都用dirname(__FILE__)
它来代替,但是运行不止一次是相当浪费的。最好用支票将其添加到某处。
回答by user20232359723568423357842364
It looks like the architecture of this application is less than optimal, but without knowing more, I can't comment on that..
看起来这个应用程序的架构不是最优的,但在不了解更多的情况下,我无法对此发表评论..
I suggest defining it as a constant so that it can't be altered and is available no matter the scope.
我建议将它定义为一个常量,这样它就不能被改变并且无论范围如何都可用。
define('PROJECTFILES',__DIR__.'/projectfiles/');
Assuming:
/config.php
/projectfiles/include_me.php
假设:
/config.php
/projectfiles/include_me.php
include(PROJECTFILES.'include_me.php');
Keep in mind that __DIR__
will reference the directory that config.php
is in. If config.php
is the parent folder of projectfiles
then the above will work.
请记住,这__DIR__
将引用所在的目录config.php
。如果config.php
是 的父文件夹,projectfiles
则上述内容将起作用。