首先准备一个要包含的文件a.php,文件内容如下
<?php $a = 1; ?>
测试require_once,内容如下
<?php for($i=1; $i<=10;$i++) { require_once('a.php'); echo $a++; }
输出结果如下,因为只有第一次包含有效,以后的包含就都无效了
12345678910
测试require,内容如下
<?php for($i=1; $i<=10;$i++) { require('a.php'); echo $a++; }
输出结果如下,每次都要执行包含,所以输出都是1
1111111111
把require和require_once换成include和include_once执行的效果是一样的
2. include和require之间的区别只是对错误的处理方式不一样
require
<?php require('b.php'); echo "contiue code ";
执行结果如下,continue code这句话并没有输出,说明require包含文件如果遇到错误,后面的代码就不执行了
PHP Warning: require(b.php): failed to open stream: No such file or directory in /home/lxy/htdocs/test.php on line 2 PHP Fatal error: require(): Failed opening required 'b.php' (include_path='.:') in /home/lxy/htdocs/test.php on line 2
include
<?php include('b.php'); echo "contiue code ";
执行结果如下,continue code输出了
PHP Warning: include(b.php): failed to open stream: No such file or directory in /home/lxy/htdocs/test.php on line 3 contiue code PHP Warning: include(): Failed opening 'b.php' for inclusion (include_path='.:') in /home/lxy/htdocs/test.php on line 3