1. Overview of file inclusion
In actual development, it is often necessary to put the common code in the program into a file, and use the files of these codes Just include this file. This method helps improve the reusability of code and brings great convenience to code writing and maintenance. In PHP, there are four methods: require, require_once, include, and include-once to include a file.
Let’s compare their differences:
##Note: 1, use less_ Once brings once because it will consume more resources to do detection work.
2. Introduction to the functions of the four methods
Note: It is recommended that students copy the code locally Test
Create a 1.php file and write two functions in it:<?php //functions.php文件 function demo(){ echo 'aaaa'; } function test(){ echo 'cccdddd'; } ?>In the same directory as the above php file, I will create another 2 The .php file includes the 1.php file. In this way, my functions can be placed specifically in 1.php. When these functions are needed, I will include them from there:
<?php include '1.php'; //可以直接调用 demo(); test(); ?>I have learned the function of include through the above example. Next, we compare include and require: In the code, we first use include to include the non-existent test.php file,
<?php include '1.php'; include 'test.php'; //可以直接调用 demo(); test(); ?>The local output result: Use require to include the non-existent test.php file: By comparing the above example, we found:
If the test.php file does not exist include will issue a warning and continue to execute the demo() and test() functions.
And require directly reports an error, and the demo() and test() functions cannot continue to execute.
<?php include '1.php'; include '1.php'; //可以直接调用 demo(); test(); ?>Result:
Change to include_once and try again:
<?php include_once '1.php'; include_once '1.php'; //可以直接调用 demo(); test(); ?>Output: The prompt in the above picture is that the function demo cannot be redefined ().
As we mentioned in the function definition chapter, a function cannot be defined twice, otherwise an error will be reported. Because we included 3_1.php twice, it was executed twice, so this error was reported.
The reason why include_once does not report an error is because it detects that functions.php has been included before and no longer includes it.
As for the functions of require and require_once, can you use your smartest little brain to deduce them? require_once has two characteristics:
1. The included file must exist, otherwise execution will stop
2. Duplicate inclusion checks will be done
New learning:
The difference between Include and require. include encounters an error warning, but continues to execute. Require will alarm after encountering an error and will not execute further
The difference between inlcude and include_once is to detect whether it is included repeatedly. If include_once is included repeatedly, the corresponding file will no longer be included, while include does not care about this.