In PHP, the functions of include and require are easily confused. Below I will use a classic example to deeply illustrate their differences.
When we frequently access a database, we can write the connection statement into a file
con_db.php
<?php
$dbh = mysql_connect('localhost','','');
mysql_select_db('admreqs');
?>
In actual application, we can call this file in the program.
For example, require("con_db.php") or include("con_db.php)
, the effect of the two functions is almost the same.
But if you use
filename.php
<?php
like this
require("con_db.php")
function myfun($par1,$par2)
{Contains statements for database processing}
.....
myfun($par1,$par2);
.....
myfun($p1,$p2);
?>
The file cannot continue to be executed when it reaches myfun, because the external variables cannot be obtained in the function (the same is true for include). Unless $dbh is passed to the function as a variable. This increases the complexity of calling functions.
We can solve this problem by putting require or include inside the function.
If include is used, the first function call of the file will pass smoothly, but the second call will not be executed. The reason is that the database cannot be opened again without closing it. In other words, con_db.php is executed twice. Replace include with require and everything is fine.
In other words, require is similar to a pre-scan. When the program is executed, whether inside or outside the function, the require file will be executed first and only once. And include calls the file every time it is executed. That is, after this execution, the next time it is executed to this point, it will be executed again.
Therefore, if there are certain statements in a loop that you only want to execute once, you can just include them with require.