Open In App

Why require_once() function is so bad to use in PHP ?

Last Updated : 15 Nov, 2019
Improve
Improve
Like Article
Like
Save
Share
Report

The require_once() function is an inbuilt function in PHP which is useful in case if we want to include a PHP file in another one i.e. when we need to include a file more than once in PHP script. It is used to check if the file is included more than once or not as it ignores all the inclusions while running the script if the file is already included.

Syntax:

require_once('File name with file path');

Parameters: This function accepts a single parameter ‘file name with path’. This is the file that we want to include in our PHP script. It is a string type parameter.

Return Value: If the called file is found and further if the file is already included, then the function would return the Boolean True and if the file is not included, then the function would include the file and return True. But if the called file is not found, then a fatal error will arise and no output will display and the execution halts returning Boolean False.

Below programs illustrate the require_once() function in PHP:

File Name: my_file.inc.php

Program:




<?php 
  
// Content of the PHP file
echo "Welcome To GeeksforGeeks"
?>


The above file my_file.inc.php included twice with require_once() function in the following file index.php. But from the output, you will get the second instance of inclusion ignored since require_once() function ignores all the similar inclusions after the first one.

File Name: index.php




    
<?php 
  
// Include the file
  
require_once('my_file.inc.php'); 
require_once('my_file.inc.php'); 
  
?> 


Output:

Welcome To GeeksforGeeks

Why require_once() function is so bad to use?

  • The require_once() function puts a lot of load on the server while including all the files.
  • The functionality of require_once() function works inappropriately when used inside repetitive function when storing variables.

File Name: my_file.php
Example:




    
<?php 
  
// Content of the file
$var = 'GFG'
  
?>


File Name: check.php




<?php
  
function func() {
    require_once('my_file.php');
    return $var;
}
  
for($i = 1; $i <= 3; $i++) {
    echo func() . "<br>";
}
  
?>


Output:

GFG

By replacing the require_once() function with the require() function in the above example, we can make sure the variable $var is available at each function call.

File Name: check2.php




<?php
  
function func() {
    require('my_file.php');
    return $var;
}
  
for($i = 1; $i <= 3; $i++) {
    echo func() . "<br>";
}
  
?>


Output:

GFG
GFG
GFG

The require_once() function is slower in comparison to require() or include() function as it checks if the file is already included or not every time the script calls the function.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads