Home  >  Article  >  Backend Development  >  What are the differences between include() and require() in PHP?

What are the differences between include() and require() in PHP?

WBOY
WBOYOriginal
2016-07-25 08:57:391119browse
  1. if($something){
  2. include("somefile");
  3. }
Copy the code

But no matter what the value of $something is, the following code will include the file somefile into the file:

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

The following interesting example fully illustrates the difference between these two functions.

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

in this paragraph In the code, the program will include the same file every time it loops. Obviously this is not the programmer's original intention. From the code we can see that this code hopes to include different files in each loop. If you want to complete this function, you must turn to the function include():

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

3, error reporting method For example, write two php files named test1.php and test2.php. Note that there should not be a file named test999.php in the same directory. test.php

  1. include ("test999.php");
  2. echo "abc";
  3. ?>
Copy code

test2.php

  1. require ("test999.php")
  2. echo "abc";
  3. ?>
Copy the code

Browse the first file because the test999.php file was not found , we see the error message, and at the same time, abc is displayed below the error message. What you see may be similar to the following: Warning: include(test1aaa.php) [function.include]: failed to open stream: No such file or directory in D:WebSitetest.php on line 2 Warning: include() [function.include]: Failed opening ‘test1aaa.php’ for inclusion (include_path=’.;C:php5pear’) in D:WebSitetest.php on line 2 abc

Browse the second file. Because the test999.php file was not found, we saw the error message. However, abc was not displayed below the error message. What you saw may be similar to the following: Warning: require(test1aaa.php) [function.require]: failed to open stream: No such file or directory in D:WebSitetest.php on line 2 Fatal error: require() [function.require]: Failed opening required ‘test1aaa.php’ (include_path=’.;C:php5pear’) in D:WebSitetest.php on line 2

Summary: The difference between include and require: When include introduces a file, if it encounters an error, it will give a prompt and continue to run the following code. When require introduces a file, if an error is encountered, a prompt will be given and the code below will stop running.



Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn