【问题标题】:How to tell if a file has already been required?如何判断文件是否已被要求?
【发布时间】:2011-10-12 23:57:50
【问题描述】:

我创建了一个 php 全局文件 (globs.php),并且在我的所有页面中都需要它。 但是,某些页面现在包含其他页面,并且当它再次尝试要求 globs.php 时出现错误。

如何判断是否需要文件?那样的话,如果 !required('globs.php') require('globs.php') 我可以做到。

【问题讨论】:

  • 你可以控制 require 语句吗?如果是这样,您可以使用 require_once() 代替。

标签: php require


【解决方案1】:

改用require_once

_require_once_ 语句与 require 相同,只是 PHP 会检查文件是否已被包含,如果是,则不再包含(要求)它...

【讨论】:

    【解决方案2】:

    array get_included_files ( void )

    http://www.php.net/manual/en/function.get-included-files.php

    获取使用includeinclude_oncerequirerequire_once 包含的所有文件的名称

    返回值

    返回所有文件名的数组。

    最初调用的脚本被视为“包含文件”,因此将列出 以及 include 和 family 引用的文件。

    多次包含或需要的文件仅在返回的数组中显示一次。


    get_included_files()例子

    <?php
    // This file is abc.php
    
    include 'test1.php';
    include_once 'test2.php';
    require 'test3.php';
    require_once 'test4.php';
    
    $included_files = get_included_files();
    
    foreach ($included_files as $filename) {
        echo "$filename\n";
    }
    
    ?>
    

    上面的例子会输出:

    abc.php
    test1.php
    test2.php
    test3.php
    test4.php
    

    【讨论】:

    • 这应该被认为是问题的答案。如果这包括一个自定义函数来实现单个回调将使它更简单。例如,函数 check_include($file) { $include_files = get_included_files();返回 in_array($file, $include_files); }
    【解决方案3】:

    最好的解决方案是 require_once(),它使用与 require() 相同的语法,但会自动执行您所说的检查。

    如果你真的需要知道它是否已经被需要,我建议在你包含的文件中定义一个常量并检查它的值。

    【讨论】:

      【解决方案4】:

      假设您要包含的文件中定义了一个函数,您也可以快速进行

       if (!function_exists('foo')) {
           require('bar.php');
       }
      

      使用最适合您的设置。

      【讨论】:

      • 我在一个类上使用了 WisdomPanda 的方法,我的例子使用了 JSMIN if(!method_exists('JSMIN', 'minify')) { require_once('libs/JSMin.php'); }
      【解决方案5】:

      你也可以制作自己的 require_file 函数:

      <?php
      function require_file($file_path){
          static $required_files=array();
          if(!isset($required_files[$file_path])){
              require $file_path;
              $required_files[$file_path]=true;
              return true;
          }
          return false;
      }
      ?>
      

      【讨论】:

      • 这个函数已经在 PHP 中为你实现了:php.net/manual/en/function.get-included-files.php 看我的回答。
      • 这只有在你使用它来包含所有内容时才有效。一旦您将 composer 或 PSR-4 或任何其他管理文件包含的东西添加到混音中,这立即变得完全不可靠。只需使用内置的。
      猜你喜欢
      • 1970-01-01
      • 2011-05-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-04
      • 2017-03-29
      • 2020-09-21
      • 1970-01-01
      相关资源
      最近更新 更多