Saturday 10 September 2016

Differences between require, require_once, include, include_once?

All these functions are used to include the files in the PHP page, however, there is slight difference between these functions.
Difference between require and include is that if the file you want to include is not found then include function give you warning and executes the remaining code in of php page where you write the include function. While require gives you fatal error if the file you want to include is not found and the remaining code of the php page will not execute.
If you have many functions in the php page then you may use require_once or include_once. There functions only includes the file only once in the php page. If you use include or require then may be you accidentally add two times include file so it is good to use require_once or include_once which will include your file only once in php page, can avoid problems with function redefinitions, Variable value reassignments, etc. Difference between require_once and include_once is same as the difference between require and include.
In general, it would be better to use require(), when, the website needs that file to run. Ex : Site wide configuration files. When it is less critical, such as footers, menus, it would be better to use include(), where the website might not look great if the menu does not get included, however, it would still display the information to people.
Ex for diff between include() and include_once():

Let us create one PHP file and name it as data.php . Here is the content of this file
<?
echo “Hello <br>”; // this will print Hello with one line break
?>
Now let us create one more file and from that we will be including the above data.php file . The name of the file will be inc.php and the code is given below.
<?
include “data.php”; // this will display Hello once
include “data.php”; // this will display Hello once
include “data.php”; // this will display Hello once
include_once “data.php”; // this will not display as the file is already included.
include_once “data.php”; // this will also not display as the file is already included.
?>
So here in the above code the echo command displaying Hello will be displayed three times and not five times. The include_once() command will not include the data.php file again.

No comments:

Post a Comment

Your comment is so valuable as it would help me in my growth of knowledge.