php - PHP:如何改变 include/require 函数的搜索行为?
问题描述
标准 include 或 require 函数首先在 include_path 变量中设置的目录中查找包含文件。之后,它在当前目录中搜索文件。
// Standard behaviour
inlcude "needed_file.php";
// 1. Looking for in include_path directories
// ...
// 2. Looking for in the current directories
// ...
但是是否有可能实现相反的行为:首先查看当前目录,然后查看 include_path 变量中的目录?
// 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_path 中,则应调用最后一个文件。
// 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";
?>
任何建议如何改进此代码?
解决方案
但是是否有可能实现相反的行为:首先查看当前目录,然后查看 include_path 变量中的目录?
使当前目录成为此设置包含的目录列表中的第一个。
http://php.net/manual/en/ini.core.php#ini.include-path:
用一个 。在包含路径中允许相对包含,因为它表示当前目录。
此设置的默认值为.;/path/to/php/pear
,因此将首先搜索当前目录。(在 unix 系统上,分隔符是:
代替;
)
如果您在预先不知道配置的系统上需要它,请检查第一个条目是否为 a .
,如果不是,则添加它。(您可能希望确保它不会在列表的后面再次出现,以免同一个目录被搜索两次。)
可以使用 get_include_path 和 set_include_path,或者使用 ini_get 和 ini_set。
推荐阅读
- javascript - 如何在不使用 JSX 的情况下编写 ReactJS 函数组件?
- python - 如何使用 Beautiful Soup 从 href 标签下的标签中提取字符串?
- office365 - OneNote 目前无法同步您的笔记。我们会继续努力。(错误代码:0xE0000007 9wgyi)
- android - 哪个分区或路径只有系统应用程序可以访问/读取android中的数据
- firebase - 我正在使用 Flutter 开发一个药物递送应用程序,但在购物车屏幕中遇到了一些问题
- react-native - FlatList 自动更新或重新渲染本机反应
- azure-sql-database - 使用 POLYBASE 将数据从 Azure SQL db 复制到 Azure Synapse 时保留空字符串
- kotlin - 我们可以制作一个模板函数来合并任意两个 T 对象吗?
- python - m4a文件中的帧字节流应该转换成什么数据类型?
- flutter - 如何使用预填充的 sqlite 数据库并从 Flutter 中的表中获取数据?