检查是否存在包含(或要求)

Min*_*ure 44 php exists require include

在调用之前如何检查include/require_once是否存在,我尝试将其放入错误块中,但PHP不喜欢它.

我认为file_exists()可以付出一些努力,但这需要整个文件路径,并且无法轻松地将相对包含传递给它.

还有其他方法吗?

Joh*_*set 56

我相信file_exists确实可以使用相对路径,但你也可以尝试这些方面的东西......

if(!@include("script.php")) throw new Exception("Failed to include 'script.php'");

...不用说,您可以将异常替换为您选择的任何错误处理方法.这里的想法是if-statement验证文件是否可以被包含,并且通常输出的任何错误消息include都通过为其加上前缀来抑制@.

  • @Gumbo我认为在语言结构中使用parantheses是很好的做法,就像我对`echo()`和`print()`一样. (7认同)
  • 最好使用`include_once`或`require_once`,这在使用`OOP`概念并避免再次重新声明类时会很有用. (3认同)
  • 你不需要围绕`include`参数值的括号.`include`不是一个函数,而是一个像`echo`这样的语言结构. (2认同)
  • 我不确定这是一个很好的解决方案:你不会看到致命的错误. (2认同)

小智 9

您还可以检查包含文件中定义的任何变量,函数或类,并查看包是否有效.

if (isset($variable)) { /*code*/ }
Run Code Online (Sandbox Code Playgroud)

要么

if (function_exists('function_name')) { /*code*/ }
Run Code Online (Sandbox Code Playgroud)

要么

if (class_exists('class_name')) { /*code*/ }
Run Code Online (Sandbox Code Playgroud)


Ste*_*AIS 9

查看stream_resolve_include_path函数,它使用与include()相同的规则进行搜索.

http://php.net/manual/en/function.stream-resolve-include-path.php


Yac*_*oby 6

file_exists当它相对于当前工作目录时,它将检查所需文件是否存在,因为它与相对路径一起正常工作.但是,如果包含文件位于PATH的其他位置,则必须检查多个路径.

function include_exists ($fileName){
    if (realpath($fileName) == $fileName) {
        return is_file($fileName);
    }
    if ( is_file($fileName) ){
        return true;
    }

    $paths = explode(PS, get_include_path());
    foreach ($paths as $path) {
        $rp = substr($path, -1) == DS ? $path.$fileName : $path.DS.$fileName;
        if ( is_file($rp) ) {
            return true;
        }
    }
    return false;
}
Run Code Online (Sandbox Code Playgroud)


Ali*_*xel 5

file_exists()使用相对路径,它还会检查目录是否存在.is_file()改为使用:

if (is_file('./path/to/your/file.php'))
{
    require_once('./path/to/your/file.php');
}
Run Code Online (Sandbox Code Playgroud)