在PHP编程中include和require都用于文件的引入。比如引入我们的数据库操作类库,引入我们的常用函数,节省多次编写代码的工作量。
但是当它们引入失败的时候,会有如下不同:
- include只生成一个警告,即E_WARNING,并继续执行脚本。
- require 生成一个致命错误,即 E_COMPILE_ERROR,并停止执行脚本。
还有一个不同点是引入的次数。
- require只会读取一次文件,
- include每次都会读取。
<?php
include("db.php");
echo "include 引入失败继续执行了吗?";
?>
输出Warning: include(db.php): failed to open stream: No such file or directory in D:\phpstudy_pro\WWW\include.php on line 2
Warning: include(): Failed opening 'db.php' for inclusion (include_path='.;C:\php\pear') in D:\phpstudy_pro\WWW\include.php on line 2
include 引入失败继续执行了吗?
Warning: include(): Failed opening 'db.php' for inclusion (include_path='.;C:\php\pear') in D:\phpstudy_pro\WWW\include.php on line 2
include 引入失败继续执行了吗?
我们看到include引入失败,但是程序还是继续执行了。
接下来看require引入失败还会继续执行吗?
<?php
require("db.php");
echo "require引入失败继续执行了吗?";
?>
输出Warning: require(db.php): failed to open stream: No such file or directory in D:\phpstudy_pro\WWW\require.php on line 2
Fatal error: require(): Failed opening required 'db.php' (include_path='.;C:\php\pear') in D:\phpstudy_pro\WWW\require.php on line 2
Fatal error: require(): Failed opening required 'db.php' (include_path='.;C:\php\pear') in D:\phpstudy_pro\WWW\require.php on line 2
从结果来看,require失败后,程序并没有继续执行了。