PHP Tutorials: include_once and require_once

While dealing with big programs/projects there might be situations when you include a file(s) multiple times. It may create conflict and halt the program from running. The include_once and require_once statement helps you ignoring the conflict if a file got included multiple times in a single program.

The include_once and require_once statement works very similar to include and require statement the only difference is the number of times it includes the file into a program.

Let us take an example

<?php
//functions.php
function site_title(){
    return "LakBlog.com";
}
?>
<?php
// Including file
require "functions.php";
// Calling the function
echo site_title(); // Output: LakBlog.com
echo "<br>";
 
// Including file once again
require "functions.php";
// Calling the function
echo site_title(); // Doesn't execute
?>

The above program will give you a fatal error. “Fatal error: Cannot redeclare site_title()“. This is because you included the file twice in a single program. The program consider the file as an individual file both the times.

<?php
// Including file
require_once "functions.php";
// Calling the function
echo site_title(); // Output: LakBlog.com
echo "<br>";
 
// Including file once again
require_once "functions.php";
// Calling the function
echo site_title(); // Output: LakBlog.com
?>

The program will execute successfully.

Leave a Reply

Your email address will not be published. Required fields are marked *