Home > Article > Backend Development > What are the ways to import files in php
The methods of introducing files in PHP are: include, require, include_once, and require_once.
Difference introduction:
include and require
include has a return value, while require does not.
include will generate a warning (E_WARNING) when loading a file fails, and the script will continue to execute after the error occurs. So include is used when you want to continue execution and output results to the user.
//test1.php <?php include './tsest.php'; echo 'this is test1'; ?> //test2.php <?php echo 'this is test2\n'; function test() { echo 'this is test\n'; } ?> //结果: this is test1
require will generate a fatal error (E_COMPILE_ERROR) when loading fails, and the script will stop executing after the error occurs. Generally used when subsequent code depends on the loaded file.
//test1.php <?php require './tsest.php'; echo 'this is test1'; ?> //test2.php <?php echo 'this is test2\n'; function test() { echo 'this is test\n'; } ?>
Result:
include and include_once
include loaded files will not be judged Whether it is repeated or not, as long as there is an include statement, it will be loaded once (even if repeated loading may occur). When include_once loads a file, there will be an internal judgment mechanism to determine whether the previous code has been loaded.
It should be noted here that include_once is judged based on whether a file with the same path has been introduced before, rather than based on the content of the file (that is, the content of the two files to be imported is the same. Using include_once will still introduce two files. indivual).
//test1.php <?php include './test2.php'; echo 'this is test1'; include './test2.php'; ?> //test2.php <?php echo 'this is test2'; ?> //结果: this is test2this is test1this is test2 //test1.php <?php include './test2.php'; echo 'this is test1'; include_once './test2.php'; ?> //test2.php <?php echo 'this is test2'; ?> //结果: this is test2this is test1 //test1.php <?php include_once './test2.php'; echo 'this is test1'; include './test2.php'; ?> //test2.php <?php echo 'this is test2'; ?> //结果: this is test2this is test1this is test2 //test1.php <?php include_once './test2.php'; echo 'this is test1'; include_once './test2.php'; ?> //test2.php <?php echo 'this is test2'; ?> //结果: this is test2this is test1
require and require_once: The difference is the same as include and include_once.
For more related tutorials, please visit php Chinese website.
The above is the detailed content of What are the ways to import files in php. For more information, please follow other related articles on the PHP Chinese website!