require() 函数
require() 函数与 include() 相同,不同的是它对错误的处理方式。
include() 函数会生成一个警告(但是脚本会继续执行),而 require() 函数会生成一个致命错误(fatal error)(在错误发生后脚本会停止执行)。
如果在您通过 include() 引用文件时发生了错误,会得到类似下面这样的错误消息:
PHP 代码:
<html> <body> <?php include("wrongFile.php"); echo "Hello World!"; ?> </body> </html>
错误消息:
Warning: include(wrongFile.php) [function.include]: failed to open stream: No such file or directory in C:/home/website/test.php on line 5 Warning: include() [function.include]: Failed opening 'wrongFile.php' for inclusion (include_path='.;C:/php5/pear') in C:/home/website/test.php on line 5 Hello World!
请注意,echo 语句依然被执行了!这是因为警告不会中止脚本的执行。
现在,让我们使用 require() 函数运行相同的例子。
PHP 代码:
<html> <body> <?php require("wrongFile.php"); echo "Hello World!"; ?> </body> </html>
错误消息:
Warning: require(wrongFile.php) [function.require]: failed to open stream: No such file or directory in C:/home/website/test.php on line 5 Fatal error: require() [function.require]: Failed opening required 'wrongFile.php' (include_path='.;C:/php5/pear') in C:/home/website/test.php on line 5
由于在致命错误发生后终止了脚本的执行,因此 echo 语句不会执行。