如何判断文件是否已被要求?

Ric*_*ins 5 php require

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

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

Uma*_*ang 26

请改用require_once:

_require_once_语句与require相同,除了PHP将检查文件是否已被包含,如果是,则不再包括(require)它...

  • 另外:http://www.php.net/manual/en/function.get-included-files.php (3认同)

Gre*_*reg 16

数组 get_included_files(无效)

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

获取使用include,include_once,requirerequire_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";
}

?>
Run Code Online (Sandbox Code Playgroud)

上面的例子将输出:

abc.php
test1.php
test2.php
test3.php
test4.php
Run Code Online (Sandbox Code Playgroud)


小智 -2

您还可以创建自己的 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;
}
?>
Run Code Online (Sandbox Code Playgroud)

  • 该函数已在 PHP 中为您实现:http://www.php.net/manual/en/function.get-included-files.php 请参阅我的答案。 (2认同)