简体   繁体   English

include()和require_once()问题

[英]include() and require_once() Issue

I have this situation: 我有这种情况:

/

index.php

/init (folder)

      init.php (of course inside this file i use require_once for db/function/and whatever you want to put inside)

/layout_parts (folder)

     header.php (and others common parts are inside this folder)

/my_space (folder inside layout parts)

      my_file.php

      another_file.php

/your_space (folder inside layout parts)

      your_file.php

      another_file.php

/third_space (folder inside layout parts)

      third_file.php

      another_file.php

For the index i have no problem it all works fine, but if i include header.php in one of the subfolder files my require_once(init/init.php); 对于索引我没有问题,一切都很好,但是如果我在其中一个子文件夹文件中include header.php ,则require_once(init/init.php); that is on the top of header.php won't work. 那在header.php的顶部是行不通的。

(Warning message says no such file in the directory (OF COURSE THE FILE EXIST) and it write down the subfolder directory that is not the path i expected). (警告消息说该目录中没有这样的文件(存在该文件),并且它记录了子文件夹目录,该目录不是我期望的路径)。

I tried echo $SERVER['DOCUMENT_ROOT]; 我试过echo $SERVER['DOCUMENT_ROOT]; to see the whole path, echo __DIR__; 要查看整个路径,请echo __DIR__; to see wich is the right path to the directory, no way out. 看到wich是目录的正确路径,没有出路。

I know is such a dummy question but if some kind heart could help me it would be great. 我知道这是一个愚蠢的问题,但是如果有一颗善良的心可以帮助我,那将是很好的。 Thanks :) 谢谢 :)

The best way to handle this would be to use absolute paths instead of relative ones. 解决此问题的最佳方法是使用绝对路径而不是相对路径。 When you use relative paths, you have to worry each time about how many levels deep you are and then have that many ../ etc. This is messy and difficult to manage, for eg, if you move a file to a different location, you have to update the includes again, based on where you are now. 当您使用相对路径时,您每次都必须担心您有多少个层次,然后又有那么多个../等。这很杂乱且难以管理,例如,如果将文件移至其他位置,您必须根据现在的位置再次更新包含文件。 This is why absolute paths are helpful. 这就是绝对路径有用的原因。

So create something like this: 因此,创建如下内容:

$appRoot = "/path/to/root/folder/";

This is the path where the index.php file is located. 这是index.php文件所在的路径。 It is the "application root", if you will. 如果需要的话,它是“应用程序根目录”。

Now, in ANY file where you want to include init.php add the following line: 现在,在要包含init.php任何文件中,添加以下行:

include_once($appRoot."init/init.php");

Ideally the $appRoot should be created in a global config located in root. 理想情况下,应在位于root的global config创建$appRoot If you do not have a structure where a univeral config can be added, it can still be messy and you might need to add absolute paths into individual files (which is not a good idea) 如果您没有可以添加统一配置的结构,那么它仍然会很混乱,您可能需要在单个文件中添加绝对路径(这不是一个好主意)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM