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

详解PHP中include与require的用法区别

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

例2,但不管$something取何值,将把文件somefile包含进文件里:

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

例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. }
复制代码

2,执行时报错方式不同

include和require的区别: include引入文件时,如果碰到错误,会给出提示,并继续运行下边的代码,require引入文件时,如果碰到错误,会给出提示,并停止运行下边的代码。 例子: 写两个php文件,名字为test1.php 和test2.php,注意相同的目录中,不要存在一个名字是test3.php的文件。 test1.php

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

test2.php

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

代码说明:

浏览第一个文件,因为没有找到test999.php文件,所以出现了报错信息,同时,报错信息的下边显示了abc,你看到的可能是类似下边的情况: Warning: include(test3.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 ‘test3.php' for inclusion (include_path='.;C:\php5\pear') in D:\WebSite\test.php on line 2 abc (下面的被执行了)

浏览第二个文件,因为没有找到test3.php文件,所以出现了报错信息,但是,报错信息的下边没有显示abc,你看到的可能是类似下边的情况: Warning: require(test3.php) [function.require]: failed to open stream: No such file or directory in D:\WebSite\test2.php on line 2

Fatal error: require() [function.require]: Failed opening required ‘test3.php' (include_path='.;C:\php5\pear') in D:\WebSite\test.php on line 2

下面的未被执行,直接结束。

总之,include时执行时调用的,是一个过程行为,有条件的,而require是一个预置行为,无条件的。



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