Home>

There are too many differences between include and require in PHP. But is this really the case?Today we will use a specific example to briefly analyze and verify

Edit command.php file first

echo "hello" .php_eol;

Then edit the console.php file

for ($i=1;$i & lt;= 3;++ $i) {
require "command1.php";
}

I originally wanted to include and execute this echo. I didn't expect to write the wrong file name.If it is require, it will report this error:

warning:require (command1.php):failed to open stream:no such file or directory in console.php on line 4
fatal error:require ():failed opening required "command1.php" (include_path=".") in console.php on line 4
php warning:require (command1.php):failed to open stream:no such file or directory in console.php on line 4
php fatal error:require ():failed opening required "command1.php" (include_path=".") in console.php on line 4

If you change require to include

for ($i=1;$i & lt;= 3;++ $i) {
include "command1.php";
}

Will report this error:

warning:include (command1.php):failed to open stream:no such file or directory in console.php on line 4
warning:include ():failed opening "command1.php" for inclusion (include_path=".") in console.php on line 4
warning:include (command1.php):failed to open stream:no such file or directory in console.php on line 4
warning:include ():failed opening "command1.php" for inclusion (include_path=".") in console.php on line 4
warning:include (command1.php):failed to open stream:no such file or directory in console.php on line 4
warning:include ():failed opening "command1.php" for inclusion (include_path=".") in console.php on line 4
php warning:include (command1.php):failed to open stream:no such file or directory in console.php on line 4
php warning:include ():failed opening "command1.php" for inclusion (include_path=".") in console.php on line 4
php warning:include (command1.php):failed to open stream:no such file or directory in console.php on line 4
php warning:include ():failed opening "command1.php" for inclusion (include_path=".") in console.php on line 4
php warning:include (command1.php):failed to open stream:no such file or directory in console.php on line 4
php warning:include ():failed opening "command1.php" for inclusion (include_path=".") in console.php on line 4

If require_once or include_once is used, as long as the include path is correct,Then the loop is executed only once.

to sum up:

Use require, if the file is not included successfully,A fatal error will be reported and the entire process will be terminated.

Use include, if the file is not included successfully,A normal warning will be reported, and subsequent code will still be executed.

If your web application uses the design method of strong dependency on files, such as mvc,Use require_once.

php
  • Previous Detailed usage of ng-include in Angularjs and implementation of multi-tab pages
  • Next Detailed NestedScrolling mechanism in Android takes you to play with nested scrolling