从包含的文件中调用包含 [英] calling include from an included file
问题描述
所以, 检查此目录结构
So, examining this directory structure
- /include_one.php
- /include_two.php
- /directory/main_file.php
- /include_one.php
- /include_two.php
- /directory/main_file.php
假设我在/directory/main_file.php 中,并且在 include_one.php 内调用include('../include_one.php');
,以包含 include_two.php .我需要打include('include_two.php);
或include('../include_two.php');
吗?
Assume that I am in /directory/main_file.php and I call include('../include_one.php');
inside of include_one.php, to include include_two.php. Do I need to call include('include_two.php);
or include('../include_two.php');
?
所以我的问题是:包含文件时,相对包含路径"是否转移到了包含文件中,还是保留在主要包含文件中?
So my question is: When including a file, is the 'relative include path' shifted to the included file, or does it remain at the main including file?
我知道最好的选择是拥有一个包含root_path的config.php,但是在现阶段这是不可能的.
I am aware that the best alternative would be to have a config.php which contains the root_path, however this is not possible at this stage.
更新:
所以,我不确定谁是对的,因为这是我的测试
update:
So, im not sure who is right, as here is my test
目录结构
/include.php
/start/start.php
/folder1/includeone.php
/folder1/folder2/includetwo.php
/include.php
/start/start.php
/folder1/includeone.php
/folder1/folder2/includetwo.php
这是每个文件的内容
start.php
<?php
echo 'including ../include.php<br />';
include('../include.php');
?>
include.php
<?php
echo 'including folder1/includeone.php<br />';
include('folder1/includeone.php');
?>
includeone.php
<?php
echo 'including folder2/includetwo.php<br />';
include('folder2/includetwo.php');
?>
includetwo.php
<?php
echo 'done<br />';
?>
,输出为
包括../include.php
包括folder1/includeone.php
包括folder2/includetwo.php
完成
including ../include.php
including folder1/includeone.php
including folder2/includetwo.php
done
推荐答案
相对包含路径"没有移到包含文件中……这意味着使用相对路径通常会以错误的方式结束.
The "relative include path" is not shifted to the included file... Which means that using relative paths generally ends badly.
我几乎一直使用的更好的解决方案是始终使用绝对路径-您可以使用__DIR__
混合亲戚路径和绝对路径,以获得包含写入该文件的目录.
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.
例如,在include_one.php
中,您将使用:
For example, in include_one.php
, you'd use :
require_once __DIR__ . '/include_two.php';
要包含与include_two.php
文件.
并且,在main_file.php
中,您将使用:
And, in main_file.php
, you'd use :
require_once __DIR__ . '/../include_one.php';
要包含一个目录中的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.
这篇关于从包含的文件中调用包含的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!