<?php
$c_file_name = 'c.php';
echo 'this is c.php, is required by ' . $file_name;
echo "<hr>";
require('../d/d.php');
?>
打印输出 "this is c.php, is required by a.php",$file_name是在a.php中定义的变量。在最后,包含了d.php。因为d文件夹在当前c.php文件的上一层,所以,按照常理,我们会理所当然的把路径写成 "../d/d.php"。但是很遗憾,会报错。原因在于,在被包含的文件中如c.php,再去包含其他文件,路径是相对于最外层的父文件来说的,也就是相对于a.php,可以理解为因为你被我包含了,所以你要以我为准。看起来很玄乎,原理其实很简单:你可以把 require('c/c.php'); 看成是c/c.php文件里的代码,这样我们的a.php看起来可以是这个样子:
<?php
$file_name = 'a.php';
echo "this is a.php";
echo "<hr>";
// require('c/c.php');
$c_file_name = 'c.php';
echo 'this is c.php, is required by ' . $file_name;
echo "<hr>";
require('../d/d.php');
?>
到此,你可以看到,我们要包含d/d.php文件时,刚才的路径是不是错误的了?因为,现在是在a.php的代码里,我们是相对于a.php文件来说的,当然,路径应该是 require('d/d.php'); 才对了。我们修改代码如下:
<?php
$file_name = 'a.php';
echo "this is a.php";
echo "<hr>";
// require('c/c.php');
$c_file_name = 'c.php';
echo 'this is c.php, is required by ' . $file_name;
echo "<hr>";
require('d/d.php');
?>