在PHP中:

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


当前回答

Include()如果不能包含该文件将抛出警告,但脚本的其余部分将运行。

require()将抛出一个E_COMPILE_ERROR并在脚本不能包含该文件时停止脚本。

如果文件已经被包含,include_once()和require_once()函数将不会第二次包含该文件。

请参见以下文档页面:

包括 需要 include_once require_once

其他回答

 

什么时候应该使用require或include? require和include函数执行相同的任务,即包含并计算指定的文件,但不同的是,当指定的文件位置无效或任何错误时,require将导致致命错误,而include将生成警告并继续代码执行。 因此,当您试图包含的文件是系统的核心,可能会对其余代码造成巨大影响时,您可以使用require函数;当您试图包含的文件是一个包含一些不太重要的代码的简单文件时,您可以使用include函数。 我个人的建议(对于不太重要的代码)是在开发阶段在代码中到处使用require函数,这样你就可以调试代码,然后在将其转移到生产环境之前用include函数替换所有的require函数,这样即使你遗漏了任何错误,也不会影响最终用户,其余的代码也能正常执行…… 什么时候应该使用require_once或require? require和require_once之间的基本区别是require_once将检查文件是否已经包含,如果已经包含,则不包含该文件,而require函数将包括该文件,而不管文件是否已经包含。 因此,当你想要一次又一次地包含某段代码时,使用require函数,而如果你只想在代码中包含某段代码一次,则使用require_once。

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

我注意到的一件事是,当使用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意味着它需要它。Require_once意味着它将需要它,但只需要它一次。包含意味着它将包含一个文件,但不需要它继续。

例子:

Require 'filename'
Require_once 'filename'
Include 'filename'

还有一个include_once函数,它只包含一个文件一次。

Include_once 'filename'

当我用手机打字时,不要用大写字母。