In real-world development, it is often necessary to put the common code in the program into a file, the files that use the code only need to include this file. This method can help to improve the reusability of code, which brings great convenience to the writing and maintenance of code.
In PHP, there are four methods of require, require_once, include, and include-once that contain a single file.
function |
contains failed |
features |
Inlcude |
Returns a warning |
The file continues to execute downward. Typically used to dynamically include |
Require |
A fatal mistake. |
The code will not continue to execute down. Usually contains extremely important files, the entire code does not want to execute |
Include_once |
Returns a warning |
In addition to the functionality of the original include, it will also do once detection, if the file has been included, no longer contain |
Require_once |
A fatal mistake. |
In addition to the original function one, will do a once detection, to prevent the file is repeatedly contained |
Attention:
- Use less _once with once because it consumes more resources to do the work of testing.
- The extra advanced include file only needs to be compiled once, because each include include will execute the corresponding code once, how to reduce the need to re-parse when the include is executed again.
* * 1.include contains function functions. **
Create a functions.php file with two functions written in it:
<?php
//functions.php文件
function demo(){
echo ‘aaaa‘;
}
function test(){
echo ‘cccdddd‘;
}
?>
In functions.php's sibling directory, I create a user.php file to include the functions.php file. So my function can be put in functions.php, where I need to use these functions, where I include them:
<?php
//user.php
include ‘functions.php‘;
//可以直接调用
demo();
test();
?>
I passed the example above and we know the features of the include. Next we compare the include and require:
In the code, we first use include to include the nonexistent test.php file
//user.p HP
include ' functions.php '
include ' test.php ' Span class= "pun";
/span>//can directly call
demo
T EST ();
Then use require to include test.php files that do not exist:
<?php
//user.php
include ‘functions.php‘;
require ‘test.php‘;
//可以直接调用
demo();
test();
?>
By comparing the above example, we find that:
If the test.php file does not exist, include warns you to continue with the demo () and test () functions.
Requre directly error, the demo () and test () function can not continue to execute.
From for notes (Wiz)
Front-end PHP primer -018-built-in function file containing function