include_once statement includes and runs the specified file during script execution. This behavior is similar to the include statement. The only difference is that if the file has already been included, it will not be included again. As the name of this statement implies, it will only be included once.
include_once can be used when the same file may be included more than once during script execution, and you want to ensure that it is only included once to avoid function duplication. Definition, variable reassignment and other issues.
Note:(Recommended learning: PHP Programming from Beginner to Master)
In PHP 4, the behavior of _once is not case-sensitive The letters are different in operating systems (such as Windows), for example:
include_once in PHP 4 running on case-insensitive operating systems
<?php include_once "a.php"; // 这将包含 a.php include_once "A.php"; // 这将再次包含 a.php!(仅 PHP 4) ?>
This behavior has been changed in PHP 5 , for example, in Windows the path is normalized first, so C:\PROGRA~1\A.php and C:\Program Files\a.php have the same implementation, and the file will only be included once.
include and include_once:
The files loaded by include will not be judged as duplicates. As long as there is an include statement, it will be loaded once (even if duplicate 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 introduced is the same, should you use include_once or not? Two will be introduced).
//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
The above is the detailed content of How to implement include_once in php. For more information, please follow other related articles on the PHP Chinese website!