PHP Tips: Deep analysis of require and include usage through examples

Source: Internet
Author: User

In PHP, the role of include and require is easier to confuse. Let me take a classic example to illustrate the difference.

When we visit a database frequently, we can write a library statement as a file

con_db.php

<?php
$DBH = mysql_connect (' localhost ', ', ', ');
mysql_select_db (' Admreqs ');
?>

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

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

At this point, the effect of two functions is similar.

But if you use this

filename.php

<?php
Require ("con_db.php")
function Myfun ($par 1, $par 2)
{contains statements for database processing}}
.....
Myfun ($par 1, $par 2);
.....
Myfun ($p 1, $p 2);
?>

The file will not continue to execute at Myfun because the outside variables (include is the same) cannot be obtained in the function. Unless you pass $DBH as a variable to a function. This increases the complexity of the calling function.

We can solve this problem by putting require or include in the function.

If you use include, the first function call of the file will pass smoothly, but the second call will not execute because it cannot be opened once when the database is not closed, that is, con_db.php executed two times. Replace include with require, everything is OK.

That is, require is similar to a pre scan, where the require file is executed and executed only once, whether in a function or function, in the execution of the program. The include is called every time the file is executed, that is, after the execution, the next execution is here, and will still be executed again.

So if you're in a loop and you want to execute only once for some statements, you can use require to include them.



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.