在PHP中:

什么时候应该使用require和include? 什么时候应该使用require_once vs. include_once?


当前回答

Include / Require你也可以包含同一个文件不止一次:

require()与include()相同,除了失败时,它也会产生致命的E_COMPILE_ERROR级别的错误。换句话说,它将停止脚本,而include()只发出一个允许脚本继续的警告(E_WARNING)。

Require_once / include_once

和include/require是一样的,除了PHP会检查文件是否已经被包含,如果已经被包含,就不再包含(require)它。

其他回答

Include()在未找到文件时将生成警告,但require_once()将生成致命错误。

另一件事是之前是否包含了file。然后require_once()将不再包含它。

我注意到的一件事是,当使用include时,我只能从包含它的文件中访问包含的文件函数。使用require_once,我可以在第二个required_once文件中运行该函数。

我建议添加

if(file_exists($RequiredFile)){
    require_once($RequiredFile);
}else{
  die('Error: File Does Not Exist');
}

因为当require_once杀死页面时,它有时会返回你的网站文件目录

下面是我做的一个自定义函数来要求文件:

function addFile($file, $type = 'php', $important=false){
    //site-content is a directory where I store all the files that I plan to require_once
    //the site-content directory has "deny from all" in its .htaccess file to block direct connections
    if($type && file_exists('site-content/'.$file.'.'.$type) && !is_dir('site-content/'.$file.'.'.$type)){
        //!is_dir checks that the file is not a folder
        require_once('site-content/'.$file.'.'.$type);
        return 'site-content/'.$file.'.'.$type;
    }else if(!$type && file_exists('site-content/'.$file) && !is_dir('site-content/'.$file)){
        //if you set "$type=false" you can add the file type (.php, .ect) to the end of the "$file" (useful for requiring files named after changing vars)
        require_once('site-content/'.$file);
        return 'site-content/'.$file;
    }else if($important){
        //if you set $important to true, the function will kill the page (which also prevents accidentally echoing the main directory path of the server)
        die('Server Error: Files Missing');
        return false;
    }else{
        //the function returns false if the file does not exist, so you can check if your functions were successfully added
        return false;
    }
}

使用的例子:

$success = addFile('functions/common');

if($success){
    commonFunction();
}else{
    fallbackFunction();
}

需要关键部分,如授权,并包括所有其他部分。

多重包含是非常糟糕的设计,必须完全避免。所以,*_once并不重要。

只需使用require和include。

因为想想如何使用include_once或require_once。 查找保存包含的或必需的PHP文件的日志数据。 这比include和require要慢。

if (!defined(php)) {
    include 'php';
    define(php, 1);
}

就像这样用…

Require的开销比include大,因为它必须首先解析文件。用包含替换require通常是一种很好的优化技术。