代码之家  ›  专栏  ›  技术社区  ›  Ivan Z

PHP:如何更改include/require函数的搜索行为?

php
  •  0
  • Ivan Z  · 技术社区  · 7 年前

    标准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";
    ?>
    

    有没有关于如何改进此代码的建议?

    1 回复  |  直到 7 年前
        1
  •  1
  •   04FS    7 年前

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

    制作 当前目录是此设置包含的目录列表中的第一个目录。

    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。

    推荐文章