calling include from an included file

孤者浪人 提交于 2019-11-29 01:04:53
Pascal MARTIN

The "relative include path" is not shifted to the included file... Which means that using relative paths generally ends badly.

A better solution, that I use almost all the time, is to always work with absolute paths -- and you can mix relatives and absolute paths using __DIR__, to get the directory that contains the file where this is written.


For example, in include_one.php, you'd use :

require_once __DIR__ . '/include_two.php';

To include the include_two.php file that's in the same directory as include_one.php.


And, in main_file.php, you'd use :

require_once __DIR__ . '/../include_one.php';

To include the include_one.php file that's one directory up.


With that, your includes will work, no matter from which file they are called.

I am using this code:

if(!isset($TO_HOME_DIR)) $TO_HOME_DIR="../"; 

And I include a file:

include_once($TO_HOME_DIR."common/include_one.php");

With if(!isset($TO_HOME_DIR)), it's not important how much you include a file into included file into included file into includ..... Only first file's -and main file's- $TO_HOME_DIR declaration is used.

Second advantage of this approach is, if you change directory of file, you only need to change one line of code; $TO_HOME_DIR declaration. :)

The include path is relative to the first file in the include chain.

A good way to ensure the correct include path is to always include from the document root.

This is done like this:

include $_SERVER['DOCUMENT_ROOT'] . '/folder1/folder2/includetwo.php';

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!