标准include或require函数首先在include_path变量中设置的目录中查找包含的文件。然后在当前目录中搜索文件。
// Standard behaviour
inlcude "needed_file.php";
// 1. Looking for in include_path directories
// ...
// 2. Looking for in the current directories
// ...
// Necessary behaviour
inlcude "needed_file.php";
// 1. Looking for in the current directories
// ...
// 2. Looking for in include_path directories
// ...
我可以编写这样的脚本来完成此任务:
function include_file_inverted( $filename ) {
// Looking for a file in the curret dir
if (file_exists(dirname(__FILE__) . $filename)) {
include (dirname(__FILE__) . $filename);
} else {
// Looking for a file in the include_path
include $filename;
}
}
但是,还有其他可能反转包含函数的搜索行为吗?
使现代化
dirname(__FILE__)
__DIR__
有必要使用
getcwd()
. 因为该函数可以在其他包含的文件中描述。
// This function is described in ./admin/ directory,
// but it is called from other places.
function include_file_inverted( $filename ) {
// Looking for a file in the curret dir
if (file_exists(getcwd() . $filename)) {
include (getcwd() . $filename);
} else {
// Looking for a file in the include_path
include $filename;
}
}
更新2
我稍微改变一下我的问题。
如果当前目录中缺少所需的文件,并且该文件仅位于include_路径中,则应调用最后一个文件。
// Main working script try to include needed file
include "the_needed_file.php";
// It is located in the included_path and is called from where.
/{included_path}/the_needed_file.php
如果需要的文件在当前目录中,它会执行一些操作,然后它应该在included_path目录中包含同名的文件。
// Main working script try to include needed file
include "the_needed_file.php";
// the_needed_file is in the current directory.
// {current_dir}/the_needed_file.php
<?
// It does something
// ...
// And it includes file from a system directory decribed in include_path
// When I write this code
include "the_needed_file.php";
// it recursively calls the current file. It is an error.
// So I need to write something like that
include "/{included_path}/the_needed_file.php";
?>
有没有关于如何改进此代码的建议?