在PHP中:
什么时候应该使用require和include? 什么时候应该使用require_once vs. include_once?
在PHP中:
什么时候应该使用require和include? 什么时候应该使用require_once vs. include_once?
当前回答
在PSR-0 / PSR-4自动加载器时代,如果您所需要的只是让一些函数/类对您的代码可用,则可能完全没有必要使用任何语句(当然,如果您仍然使用PHP作为模板引擎,则仍然需要在引导文件中require_once自动加载器本身并包含模板)。
其他回答
Include()如果不能包含该文件将抛出警告,但脚本的其余部分将运行。
require()将抛出一个E_COMPILE_ERROR并在脚本不能包含该文件时停止脚本。
如果文件已经被包含,include_once()和require_once()函数将不会第二次包含该文件。
请参见以下文档页面:
包括 需要 include_once 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函数与不含_once函数的区别: 没有_once函数的代码将被再次包含,而有_once函数的PHP会跟踪被包含的文件,并且只包含它一次。
require和include的区别: 如果没有找到所需的文件,PHP将发出致命错误,而for include只会发出警告。
区别在于命令生成的错误。使用require,您想要使用的文件确实是必需的,因此如果找不到它,将生成一个E_ERROR。
require()与include()相同,除了失败时它也会产生致命的E_ERROR级别错误。
include只在失败时生成一个E_WARNING错误,该错误或多或少是沉默的。
因此,如果需要该文件才能使其余代码正常工作,并且您希望脚本失败,则使用该文件。
* _once ():
Include_once()可以在脚本的特定执行过程中多次包含和计算相同文件的情况下使用,因此在这种情况下,它可以帮助避免诸如函数重新定义、变量值重新赋值等问题。
当然,同样适用于require_once()。
引用:require(), include_once()
基本上,如果您需要一个错误的路径,PHP会抛出一个致命错误,并调用shutdown函数,但是当您包含一个错误的路径时,PHP将继续执行,但它只会显示一个警告,表明文件不存在。
根据英文单词require, PHP被告知页面或文件的执行取决于所需的文件。
根据我的经验,通常需要重要的文件,如配置文件、数据库类和其他重要的实用程序。