在PHP中:

什么时候应该使用require和include? 什么时候应该使用require_once vs. include_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();
}

其他回答

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

require文件必须存在,如果不存在则会显示错误;而使用include -如果文件不存在,那么页面将继续加载。

基本上,如果您需要一个错误的路径,PHP会抛出一个致命错误,并调用shutdown函数,但是当您包含一个错误的路径时,PHP将继续执行,但它只会显示一个警告,表明文件不存在。

根据英文单词require, PHP被告知页面或文件的执行取决于所需的文件。

根据我的经验,通常需要重要的文件,如配置文件、数据库类和其他重要的实用程序。

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

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

当需要加载任何类、函数或依赖项时,请使用require函数。 当你想加载模板样式的文件时,使用include函数

如果您仍然感到困惑,就一直使用require_once。