Description of the difference between require and require_once in php

  • 2021-01-06 00:29:56
  • OfStack

include() and require() : Statements include and run the specified file.
include() results in a warning and require() results in a fatal error. In other words, use require() if you want to stop processing the page if you encounter a missing file. include() is not the case, and the script continues to run.

The require_once() statement includes and runs the specified file during script execution. This behavior is similar to the require() statement, except that if the code in the file has already been included, it will not be included again.
The include_once() statement includes and runs the specified file during script execution. This behavior is similar to the include() statement, except that if the code in the file has already been included, it will not be included again. As the name of the statement implies, it will only be included once.

1. The include() function reads the specified file and executes the program.

For example: include ('/home me/myfile ');

The program code in the imported file will be executed, and when executed, the program will have the same variable range (variable scope) as the location in the source file where the include() function was called. You can import static files from the same server, or even from other servers by combining the include() and fopen() functions.

2. The function include_once() is almost identical to include()

Only one difference between include_once () function will first check to import file is already in other areas of the program to be imported, if any will not repeat import this file (this feature is very important, sometimes say you want to import the archive announced 1 some of your own defined function, so if in repeat this file to import, with a program in the second import will occur when the error message, because PHP are not allowed to repeat declared a function of the same name was 2 times).

3. The require() function reads the contents of the target file and replaces itself with the contents of the target file.

This read and substitution of the movement is in the PHP engine when compile your code, rather than in PHP engine start to perform compiled code (PHP 3.0 engine works is to compile line 1 row 1, but by the PHP 4.0 change, PHP 4.0 is to compile the whole program code is complete, then insert the compiled code, one has been completed in the process of compiling will not perform any program code). require() is typically used to import static content, while include() is good for importing dynamic program code.

4. Like the include_once() function, the require_once() function first checks to see if the contents of the target file have been imported before, and if so, it does not import the same contents again.


Related articles: