PHP - 使用上述目录的最佳方式包括
我的网站的某些部分遇到了一些问题,正在从不同的根访问某些文件,并且包含的结尾有时是这样的:
require_once ('../eggs/libs/lagger/lagger_config.php');
require_once ('../eggs/libs/lagger/lagger_init.php');
有时是这样的:
require_once("../libs/lagger/lagger_config.php");
require_once("../libs/lagger/lagger_init.php");
有没有更好的方法来解决这个问题,而不必使用:
../../
I'm having some problems with some parts of my website are accessing some files from different roots and the includes end sometimes like this:
require_once ('../eggs/libs/lagger/lagger_config.php');
require_once ('../eggs/libs/lagger/lagger_init.php');
and sometimes like this:
require_once("../libs/lagger/lagger_config.php");
require_once("../libs/lagger/lagger_init.php");
is there a better way to solve this problem, without having to use the:
../../
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
如果您有一个针对每个请求运行的文件(例如前端控制器),您可以执行以下操作:
然后,在您的个人脚本中:
If you've got a file that gets run for every request (like a front controller) you can do something like this:
Then, in your individual scripts:
最好的方法是获取基本目录,即
:
Ps 我建议这样做,因为您可以使用 ROOT 来建立一致的路径。
Best way is to get the base directory, i.e.
then:
P.s. I suggest this as you can then use ROOT to build up paths that will be consistent.
这样做的唯一好处是您只能使用
../
一次,而不是每次包含时都使用。但是,当../
的数量发生变化时,您仍然需要声明适当的路径。另一方面,如果您的脚本有权访问根目录,则可以将包含路径定义为
{root}/eggs/libs/lagger/
(其中 {root} 是根目录的路径) )并且只需设置一次,而不使用相对路径。The only benefit to this is you can use
../
only once, instead of with every include. However, when the amount of../
changes, you'll still need to declare the appropriate path.On the other hand, if your script has access to the root directory, you can define the include path as
{root}/eggs/libs/lagger/
(where {root} is the path to the root) and just set it once, without using relative paths.就像您所做的那样,相对路径是包含像您这样的文件的标准方法。
如果您不喜欢这样,我有一些项目将“INCLUDES_FOLDER”定义为绝对路径。
所以你的包含内容将变成
Relative paths, like you're doing, are the standard way of including files like you are.
If you dislike that, I've a few projects where I define the 'INCLUDES_FOLDER' to the absolute path.
So your includes would become
要么是这个,要么是设置绝对路径。
It's either this or set absolute paths.
在执行任何包含之前,将其放在脚本的顶部,这样您就不必在每个包含/需要调用中执行路径。
或者,您可以在 php.ini 级别修改
include_path
,这样它对于所有脚本都是永久的。Putting this at the top of the script, before you do any includes, will save you having to do the paths in each include/require call.
Alternatively you can modify the
include_path
at the php.ini level so it's permanent for all scripts.那么您可以定义一些可以在整个网站中使用的常量:
Well you can defined some constants you can use throughout your website: