PHP:如何更改包含/需要功能的搜索行为?

时间:2019-02-05 08:51:44

标签: php

标准include或require函数首先在include_path变量中设置的目录中查找包含的文件。之后,它将在当前目录中搜索文件。

SpringApplication.setWebApplicationType(WebApplicationType.REACTIVE)

但是有可能实现相反的行为:首先查看当前目录,然后在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()

更新2

我稍微改变了我的问题。

如果当前目录中缺少所需的文件,而仅在include_path中,则应调用最后一个文件。

// 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;
  }
}

如果所需文件在当前目录中,它将执行某些操作,然后在included_pa​​th目录中包含相同名称的文件。

// 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

任何建议如何改进此代码?

1 个答案:

答案 0 :(得分:1)

  

但是有可能实现相反的行为:首先查看当前目录,然后在include_path变量中查看目录吗?

使成为该设置包含的目录列表中第一个目录的当前目录。

http://php.net/manual/en/ini.core.php#ini.include-path

  

使用。包含路径中的允许相对包含,因为这意味着当前目录。

此设置的默认值为.;/path/to/php/pear,因此将首先搜索当前目录。 (在UNIX系统上,分隔符是:而不是;

如果在不知道配置的系统上需要此功能,请检查第一个条目是否为.,如果不是,则添加它。 (您可能要确保在列表的后面不再出现该目录,以免同一目录被搜索两次。)

可以使用get_include_path和set_include_path,也可以使用ini_get和ini_set。