首页 > 解决方案 > 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_pa​​th目录中包含同名的文件。

// 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";
?>

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

标签: 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。


推荐阅读