php 如何相对地要求PHP文件(在不同的目录级别)?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12954578/
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
How to require PHP files relatively (at different directory levels)?
提问by Boris D. Teoharov
I have the following file structure:
我有以下文件结构:
rootDIR
dir1
subdir1
file0.php
file1.php
dir2
file2.php
file3.php
file4.php
file1.phprequires file3.phpand file4.phpfrom dir2 like this :
file1.php需要file3.php和file4.php来自 dir2 像这样:
require('../../dir2/file3.php')
file2.phprequires file1.phplike this:
file2.php需要file1.php这样:
require('../dir1/subdir1/file1.php')
But then require in file1.phpfails to open file3.phpand file4.php( maybe due to the path relativeness)
但是随后 require infile1.php无法打开file3.php并且file4.php(可能是由于路径相对性)
However, what is the reason and what can I do for file2.phpso file1.phpproperly require file3.phpand file4.php?
但是,这是什么原因,我可以为file2.php如此file1.php正确的要求file3.php和做什么做些什么file4.php?
回答by Baronth
Try adding dirname(__FILE__)before the path, like:
尝试dirname(__FILE__)在路径前添加,例如:
require(dirname(__FILE__).'/../../dir2/file3.php');
It should include the file starting from the root directory
它应该包含从根目录开始的文件
回答by SharpC
For relative paths you can use __DIR__directly rather than dirname(__FILE__)(as long as you are using PHP 5.3.0 and above):
对于相对路径,您可以__DIR__直接使用而不是dirname(__FILE__)(只要您使用的是 PHP 5.3.0 及更高版本):
require(__DIR__.'/../../dir2/file3.php');
Remember to add the additional forward slash at the beginning of the path within quotes.
请记住在引号内的路径开头添加额外的正斜杠。
See:
看:
回答by hexalys
A proper advice here, is to never ever use such things as "../../" relative paths in your web apps. It's hard to read and terrible for maintenance.
一个正确的建议是永远不要在您的网络应用程序中使用诸如“../../”之类的相对路径。很难阅读并且维护起来很糟糕。
As you can attest. It makes it extremely difficult to know what you are pointing to.
If you need to change the folder level of your application, or parts of it. It's completely prone to errors, and will likely break something that is horrible to debug.
正如你可以证明的那样。这使得知道你所指的内容变得极其困难。
如果您需要更改应用程序的文件夹级别或其中的一部分。它完全容易出错,并且可能会破坏调试起来很糟糕的东西。
Instead, definea few constants in your bootstrap file for your main path(s) and then use:
相反,define在您的引导文件中为您的主路径添加一些常量,然后使用:
require(MY_DIR.'/dir2/file3.php');
Moving your app from there, is as easy as replacing your MY_DIR constants in one single file.
从那里移动您的应用程序就像在一个文件中替换您的 MY_DIR 常量一样简单。
回答by Grant
You can always use the $_SERVER['DOCUMENT_ROOT']as a valid starting point, as well, rather than resorting to a relative path. Just another option.
您也可以始终将$_SERVER['DOCUMENT_ROOT']用作有效的起点,而不是求助于相对路径。只是另一种选择。
require($_SERVER['DOCUMENT_ROOT'].'/wp-load.php');
回答by Amit Kriplani
I think your cwd is dir2. Try :
我认为你的 cwd 是 dir2。尝试 :
require("file3.php");
require("file4.php");

