In-depth analysis of the usage of require and include through examples_PHP tutorial

WBOY
Release: 2016-07-13 17:35:59
Original
1084 people have browsed it

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 database connection statement into a file

con_db.php

$dbh = mysql_connect(localhost,,);
mysql_select_db(admreqs);
?>

In actual application, we can call this file in the program.

Such as require("con_db.php") or include("con_db.php)

At this time, the effects of the two functions are almost the same.

But if used like this

filename.php

require("con_db.php")
function myfun($par1,$par2)
{Contains statements for database processing}
.....
myfun($par1,$par2);
.....
myfun($p1,$p2);
?>

When the file reaches myfun, it will not be able to continue execution 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 you use include, 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 executes two Second-rate. 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 that you only want to execute once in a loop, then you can include them with require.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/508257.htmlTechArticleIn PHP, the functions of include and require are relatively easy to confuse. Below I will use a classic example to deeply illustrate their differences. When we frequently access a database, we can use Liankuyu...
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template