[英]using php __DIR__
I'm trying to create a config.php file that defines a global variable which contains the path to a directory called "projectfiles". 我正在尝试创建一个config.php文件来定义一个全局变量,该变量包含一个名为“projectfiles”的目录的路径。 The idea is that any file can point to this directory regardless of where it is in the file tree.
我们的想法是,无论文件树在何处,任何文件都可以指向此目录。
Can I use __DIR__
for this? 我可以使用
__DIR__
吗? Would someone be willing to give me an example of how this might work? 有人愿意给我一个如何运作的例子吗? I was thinking of something like the following:
我在考虑以下内容:
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? 建议?
__DIR__
is certainly what you are looking for. __DIR__
肯定是你要找的。 Use it to provide relative paths for required files. 使用它为所需文件提供相对路径。 I would highly suggest using
require_once
or include_once
for all library files. 我强烈建议对所有库文件使用
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. 使用第一行确保您不会遇到PHP 5.2及其他问题。 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. 许多框架使用
dirname(__FILE__)
代替,但运行多次是相当浪费的。 It is better to just add it somewhere with a check. 最好只用支票将它添加到某个地方。
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 /config.php
/projectfiles/include_me.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
的父文件夹,那么上面的内容将起作用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.