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

php教程评论179 views阅读模式
  1. if($something){
  2. include("somefile");
  3. }

复制代码

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

  1. if($something){
  2. require("somefile");
  3. }

复制代码

例3,充分说明了这两个函数之间的不同。

  1. $i = 1;
  2. while ($i < 3) {
  3. require("somefile.$i");
  4. $i++;
  5. }

复制代码

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

  1. $i = 1;
  2. while ($i < 3) {
  3. include("somefile.$i");
  4. $i++;
  5. }

复制代码

2,执行时报错方式不同

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

    复制代码

    test2.php

    复制代码

    代码说明:

    浏览第一个文件,因为没有找到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是一个预置行为,无条件的。

    企鹅博客
    • 本文由 发表于 2020年8月18日 20:35:03
    • 转载请务必保留本文链接:https://www.qieseo.com/317519.html

    发表评论