使用PHP __DIR__ [英] using php __DIR__
问题描述
我正在尝试创建config.php文件,该文件定义一个全局变量,该变量包含指向名为 projectfiles的目录的路径。这个想法是,任何文件都可以指向该目录,而不管它在文件树中的位置。
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.
我可以为此使用 __ DIR __
吗?有人愿意给我一个例子,这可能如何工作吗?我在想以下内容:
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:
我想在这里定义目录: /config.php
文件
I want to define an directory here: in the /config.php
file
$projectfiles = __DIR__("projectfiles/")
然后我希望库文件能够在 /venders/library/generalfunctions.php
中使用此变量文件
Then I want a library file to be able to use this variable in /venders/library/generalfunctions.php
file
include("../../../config.php");
$file = $projectfiles/testfile.php
建议?
推荐答案
__ DIR __
当然是您想要的。使用它来提供所需文件的相对路径。我强烈建议对所有库文件使用 require_once
或 include_once
。
__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.
if( !defined( __DIR__ ) ) define( __DIR__, dirname(__FILE__) );
require_once( __DIR__ . '/../../../config.php');
.
.
.
// you code here
使用第一行可确保您不会遇到PHP的麻烦5.2并返回。这将允许您基于目录结构而不是相对于所调用的脚本来包含文件。许多框架改用 dirname(__ FILE __)
,但是多次运行很浪费。最好将其添加到带有检查的位置。
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 __DIR__的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!