Difference between include and require in PHP instance analysis and require instance analysis
Edit the command. php file first
echo 'hello'.PHP_EOL;
Edit the console. php file.
for($i=1;$i<=3;++$i){require 'command1.php';}
I originally wanted to include and execute this echo. I did not expect to write the wrong file name. If it is require, this error will be reported:
Warning: require(command1.php): failed to open stream: No such file or directory in console.php on line 4Fatal error: require(): Failed opening required 'command1.php' (include_path='.') in console.php on line 4PHP Warning: require(command1.php): failed to open stream: No such file or directory in console.php on line 4PHP 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<=3;++$i){include 'command1.php';}
The following error is reported:
Warning: include(command1.php): failed to open stream: No such file or directory in console.php on line 4Warning: include(): Failed opening 'command1.php' for inclusion (include_path='.') in console.php on line 4Warning: include(command1.php): failed to open stream: No such file or directory in console.php on line 4Warning: include(): Failed opening 'command1.php' for inclusion (include_path='.') in console.php on line 4Warning: include(command1.php): failed to open stream: No such file or directory in console.php on line 4Warning: include(): Failed opening 'command1.php' for inclusion (include_path='.') in console.php on line 4PHP Warning: include(command1.php): failed to open stream: No such file or directory in console.php on line 4PHP Warning: include(): Failed opening 'command1.php' for inclusion (include_path='.') in console.php on line 4PHP Warning: include(command1.php): failed to open stream: No such file or directory in console.php on line 4PHP Warning: include(): Failed opening 'command1.php' for inclusion (include_path='.') in console.php on line 4PHP Warning: include(command1.php): failed to open stream: No such file or directory in console.php on line 4PHP Warning: include(): Failed opening 'command1.php' for inclusion (include_path='.') in console.php on line 4
If require_once or include_once is used, the loop is executed only once if the inclusion path is correct.
Summary:
If require is used, if the file is not included successfully, a fatal error is reported, and the entire program is aborted.
Use include. If the file is not successfully included, a normal warning will be reported and subsequent code will still be executed.
Use require_once if your Web application uses the MVC design method that is highly dependent on files.