PHP8.1.21版本已发布
vue8.1.21版本已发布
jquery8.1.21版本已发布

PHP中include()与require()的区别有哪些

原创
2016-07-25 08:57:39 805浏览
  1. if($something){
  2. include("somefile");
  3. }
复制代码

但不管$something取何值,下面的代码将把文件somefile包含进文件里:

  1. if($something){
  2. require("somefile");
  3. }
复制代码

下面的这个有趣的例子充分说明了这两个函数之间的不同。

  1. $i = 1;
  2. while ($i require("somefile.$i");
  3. $i++;
  4. }
复制代码

在这段代码中,每一次循环时,程序都将把同一个文件包含进去。很显然这不是程序员的初衷,从代码中我们可以看出这段代码希望在每次循环时,将不同的文件包含进来。如果要完成这个功能,必须求助函数include():

  1. $i = 1;
  2. while ($i include("somefile.$i");
  3. $i++;
  4. }
复制代码

3,报错方式 例子,写两个php文件,名字为test1.php 和test2.php,注意相同的目录中,不要存在一个名字是test999.php的文件。 test.php

  1. include (”test999.php”);
  2. echo “abc”;
  3. ?>
复制代码

test2.php

  1. require (”test999.php”)
  2. echo “abc”;
  3. ?>
复制代码

浏览第一个文件,因为没有找到test999.php文件,我们看到了报错信息,同时,报错信息的下边显示了abc,你看到的可能是类似下边的情况: Warning: include(test1aaa.php) [function.include]: failed to open stream: No such file or directory in D:\WebSite\test.php on line 2 Warning: include() [function.include]: Failed opening ‘test1aaa.php’ for inclusion (include_path=’.;C:\php5\pear’) in D:\WebSite\test.php on line 2 abc

浏览第二个文件,因为没有找到test999.php文件,我们看到了报错信息,但是,报错信息的下边没有显示abc,你看到的可能是类似下边的情况: Warning: require(test1aaa.php) [function.require]: failed to open stream: No such file or directory in D:\WebSite\test.php on line 2 Fatal error: require() [function.require]: Failed opening required ‘test1aaa.php’ (include_path=’.;C:\php5\pear’) in D:\WebSite\test.php on line 2

小结: include和require的区别:include引入文件时,如果碰到错误,会给出提示,并继续运行下边的代码。 require引入文件时,如果碰到错误,会给出提示,并停止运行下边的代码。



声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。