include和request

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 语句不会执行。

正因为在文件不存在或被重命名后脚本不会继续执行,因此我们推荐使用 require() 而不是 include()。

posted @ 2012-08-17 13:01  zotall  阅读(554)  评论(0编辑  收藏  举报