在PHP中:
什么时候应该使用require和include? 什么时候应该使用require_once vs. include_once?
在PHP中:
什么时候应该使用require和include? 什么时候应该使用require_once vs. include_once?
当前回答
当需要加载任何类、函数或依赖项时,请使用require函数。 当你想加载模板样式的文件时,使用include函数
如果您仍然感到困惑,就一直使用require_once。
其他回答
要求生成致命错误,停止下一行执行,而没有找到文件。
包括生成警告,但没有停止下一行执行,而没有找到文件。
Require_once do与require do相同,但它将检查文件是否已经加载或是否要执行。
Include_once do与include do相同,但它将检查文件是否已经加载或是否要执行。
注意:include_once或require_once可能用于在特定脚本执行期间包含同一个文件并对其进行多次计算的情况,因此在这种情况下,它可能有助于避免诸如函数重新定义、变量值重新赋值等问题。
还有require和include_once。
所以你的问题应该是…
什么时候应该使用require和include? 什么时候应该使用require_once vs. require
这里描述了1的答案。
require()函数与include()函数相同,只是处理错误的方式不同。如果发生错误,include()函数将生成警告,但脚本将继续执行。require()生成一个致命错误,脚本将停止。
2的答案可以在这里找到。
require_once()语句与require()语句相同,只是PHP会检查文件是否已经包含,如果已经包含,则不会再次包含(require)它。
对于可重用的PHP模板,使用“include”。使用“require”表示必需的库。
“*_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();
}
Use
需要 当你的应用程序需要这个文件时,例如一个重要的消息模板或一个包含配置变量的文件,如果没有这些文件应用程序将会崩溃。 require_once 当文件包含的内容会在后续包含时产生错误时,例如。 Function important() {/* important code */}在你的应用程序中肯定是需要的,但由于函数不能被重新声明,所以不应该再次包含。 包括 当文件不是必需的,应用程序流程应该继续时,没有找到,例如 对于模板引用当前作用域的变量或其他东西非常有用 include_once 可选的依赖关系,会在后续加载时产生错误,或者可能远程文件包含,由于HTTP开销,您不希望发生两次
但基本上,什么时候用哪种取决于你。