它们之间有什么区别吗?使用它们是一个偏好的问题?使用一个优于另一个产生任何优势吗?哪个更安全?
答案 0 :(得分:180)
require
将抛出PHP致命错误。 (执行停止)
include
会生成警告。 (继续执行)
这是一个不错的illustration of include and require difference:
来自: Difference require vs. include php (by Robert; Nov 2012)
答案 1 :(得分:145)
您可以在the page of require
详细的PHP手册中找到差异:
require
与include
相同,但失败后也会产生致命的E_COMPILE_ERROR
级错误。换句话说,它会暂停脚本,而include只会发出警告(E_WARNING
),这样可以让脚本继续运行。
请参阅@efritz's answer以获取示例
答案 2 :(得分:5)
如果您不介意在没有加载文件的情况下继续运行脚本(如果它不存在等),请使用include
并且您可以(尽管您不应该)看到显示警告错误消息
使用require
表示如果脚本无法加载指定的文件,则会暂停脚本,并抛出致命错误。
答案 3 :(得分:3)
include()
和 require()
之间的区别出现在无法找到包含的文件时:include()
将发布警告 (E_WARNING) 并且脚本将继续,而 require()
将释放致命错误 (E_COMPILE_ERROR) 并终止脚本。如果包含的文件对脚本的其余部分正确运行至关重要,那么您需要使用 require()
。
答案 4 :(得分:2)
正如其他人指出的那样,唯一的区别是需要抛出一个致命的错误,包括 - 一个可捕获的警告。至于使用哪一个,我的建议是坚持包括。为什么?因为您可以发出警告并向最终用户提供有意义的反馈。考虑
// Example 1.
// users see a standard php error message or a blank screen
// depending on your display_errors setting
require 'not_there';
// Example 2.
// users see a meaningful error message
try {
include 'not_there';
} catch(Exception $e) {
echo "something strange happened!";
}
注意:例如2要工作,您需要安装错误到异常处理程序,如此处所述http://www.php.net/manual/en/class.errorexception.php
function exception_error_handler($errno, $errstr, $errfile, $errline ) {
throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
}
set_error_handler("exception_error_handler");
答案 5 :(得分:0)
<?php
$ch = curl_init(); curl_setopt($ch, CURLOPT_URL, 'localhost/test/user/user_type');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$type = curl_exec($ch);
curl_close($ch); header("Content-type: text/css; charset: UTF-8");
if($type == "admin") {
$settingButtonColor = "#990000";
}
if($type == "student") {
$settingButtonColor = "#990001";
}
if($type=="teacher") {
$settingButtonColor = "#990002";
}
?>
.sett_btn {
background-color:<?php echo $settingButtonColor;?> !important;
}
一个非常简单的代码实用示例。 将显示第一个回声。无论你使用include还是require,因为它在include或required之前运行。
要检查结果,在代码的第二行有意提供错误的文件路径或在文件名中出错。因此,显示与否的第二个回声将完全取决于您使用 require 还是 include 。
如果您使用 require ,则第二个回显将不会执行,但如果您使用 include ,无论出现什么错误,您都会看到第二个回声的结果。
答案 6 :(得分:-2)
如果Include程序不会终止并在浏览器上显示警告,另一方面,如果找不到文件,则需要程序终止并显示致命错误。