Home > Article > Backend Development > Similarities and differences between require(), include(), require_once() and include_once()_PHP Tutorial
require() and include() have many similarities, but also some differences. It's important to understand their differences, otherwise it's easy to make mistakes.
I introduce these two sentences together so that readers can compare and learn.
1.require() statement
The require() statement is used to specify the file instead of the statement itself, just like the include() statement in C language. If the URL fopen wrappers in the php configuration file php.ini is turned on (it is turned on by default), you can use the URL to specify the location of the file to achieve remote file calling.
One thing is to pay special attention when using require() and include() statements. That is, in the included file, the processor interprets the content according to the HTML mode, and returns to the PHP mode after processing the included content. So if you need to use PHP syntax in the included file, you must use the correct PHP start and end tags to include these statements.
require() and include() are a language feature in PHP, not a function. They are different from functions in many ways.
For example: the file included in require() cannot contain control structures, and statements such as return cannot be used. Using the return statement in a file included with require() will generate a processing error.
Unlike the include() statement, the require() statement will unconditionally read the contents of the file it contains, regardless of whether these statements are executed. So if you want to include different files according to different conditions, you must use the include() statement. Of course, if the statement at the location of require() is not executed, the statements in the file contained by require() will not be executed either.
require() cannot include different files according to different conditions in the loop body. The require() statement will only call the content of the file it contains when it is executed for the first time to replace the statement itself. When it is executed again, only the statement included in the first time will be executed. But the include() statement can include different files in the loop body.
The variables in the require() statement inherit the variable scope where the require() statement is located. All variables accessible at the location of the require() statement are accessible in the file included in the require() statement. If the require() statement is located inside a function, then the statements in the included file are equivalent to being defined inside the function.
The require() statement will read the file referenced by require before the PHP program is executed, so require is usually placed at the beginning of the program. Therefore, special attention should be paid to the fact that the require statement is a bit strong. Regardless of whether the program really needs the referenced files, as long as you use the require statement, it will include them! Even if you use this function to include in a conditional control statement, even if the condition is not true, the referenced file will be included! Zombies are formed. These zombies will not have any visible effect during operation, but it will obviously increase the burden, so pay special attention to this! If an inclusion error occurs using the require statement, the program will output an error message and stop running! !
If the require() statement includes the remote file by declaring the URL of the file, and the remote server interprets the file according to the PHP code, the content contained in the local PHP file is the result of processing on the remote server . For example:
/*
This example assumes that some_server server can interpret .php files but not .txt files. In the remote file
requires variables $varfirst and $varsecond
*/
/*Cannot be executed correctly, the remote server does not process .txt files*/
require("http://some_server/file .txt?varfirst=1&varsecond=2");
/*Incorrect, you can only find the file.php file on the local machine*/
require("file.php?varfirst=1&varsecond=2 ");
/*Correct statement*/
require("http://some_server/file.php?varfirst=1&varsecond=2");
$varfirst=1 ;
$varsecond=2;
require("file.txt"); /*Correct statement*/
require("file.php"); /*Correct statement*/
Originally in php3.0, files included in require() can use the return statement, but the condition is that the return statement cannot appear inside {}, but must appear in the global scope of the included file. This function of require() has been canceled in php4.0, but it can still be implemented using include().
2.include() statement
The include() statement and the require() statement have many similarities. Except for the parts in the above require() statement that are not explicitly stated not to be applicable to include(), the functions of the require() statement are fully applicable to the include() statement. The following describes the functions and features of the include() statement that are not available in the require() statement.
The include statement will only read in the files to be included when it is executed.To facilitate error handling, use the include statement. If an include error occurs, the program will skip the include statement. Although the error message will be displayed, the program will continue to execute!
The PHP processor will reprocess it every time it encounters an include() statement, so you can use include() in conditional control statements and loop statements to include different files according to different situations.
For example:
$files=array('first.php','second.php','third.php');
for($i=0;$ i
include $files[$i];
}
?>
In php3.0 and php4.0 include( ) statement can use the return statement to return a value and stop executing the content below the included file. But php3.0 and php4.0 handle such situations differently. In php3.0 the return statement cannot be contained within {} unless it is in a function, because then it represents the return value of the function rather than the return value of the file. In php4.0, there is no such restriction. Users can even return a number in the file, just like the return value of a function. Such statements usually report errors in
php3.0. The following is an example:
Assume that the included file is test.inc and the main file main.php is located in a directory. The content of test.inc is as follows:
test.inc
echo "Before the return
n";
if(1)
{
return 27 ;
}
echo "After the return
n";
?>
Suppose the main.php file contains the following statement:
$retval=include('test.inc');
echo "File returned:'$retval'
n";
?>
The php3.0 interpreter will The second line reports an error and cannot get the return value of the include() statement. But in php4.0, you will get the following result:
Before the return
File returned: '27'
Let’s assume that main.php is changed to:
include( 'test.inc');
echo "Back in main.html
n";
?>
The output in php4.0 is:
Before the return
Back in main.html
The output result in php5.0 is also:
Before the return
Back in main.html
The output result in php3.0 Is:
Before the return
27Back in main.html
Parse error:parse error in /apache/htdocs/phptest/main.html on line 5
The above appears The error is because the return statement is inside {} and not inside a function. If {} is removed so that it is located at the outermost layer of test.inc, the output result is:
Before the return
27Back in main.html
The reason why 27 appears is because in php3.0 Include() return is not supported.
3. require_once() and include_once() statements
require_once() and include_once() statements correspond to require() and include() statements respectively. The require_once() and include_once() statements are mainly used when multiple files need to be included, which can effectively avoid errors in repeated definitions of functions or variables caused by including the same piece of code.For example: If you create two files util.inc and fool.inc, the program codes are:
util.inc:
define(PHPVERSION,floor(phpversion()));
echo "GLOBALS ARE NICE
n";
function goodTea()
{
return "Olong tea tastes good!";
}
?>
and fool.inc:
require ("util.inc");
function showVar($var)
{
if(PHPVERSION==4)
{
print_r($var);
} }
else
} {
var_dump($var);
} }
}
?>
Then in error_require .php contains these two files:
require("fool.inc");
require("util.inc");//This sentence will generate an error
$foo=array("1",array("complex","quaternion"));
echo "this is requiring util.inc again which is also
n";
echo "required in fool .incn";
echo "Running goodTea:".goodTea()."
n";
echo "Printing foo:
n";
showVar($foo);
?>
When running error_require.php, the output is as follows:
GLOBALS ARE NICE
GLOBALS ARE NICE
Fatal error:Cannot redeclare goodTea() in util.inc on line 4
If you use the require_once() statement instead of the require() statement, the above error will not occur. We changed the require() statement in error_require.php and fool.inc to require_once() statement and renamed it to error_require_once.php. The result is as follows:
GLOBALS ARE NICE
this is requiring util.inc again which is also
required in fool.inc Running goodTea:Olong tea tastes good!
Printing foo:
Array([0] => 1 [1] => Array ([0] => ; complex [1] = quaternion))
The syntax of the include_once() statement is similar to the include() statement. The main difference is to avoid repeated definitions of functions or variables caused by including a file multiple times.
The require_once statement has a reference chain, which ensures that the file is added to your program only once and avoids conflicts between variable values and function names.
Like the require_once statement, the include_once statement extends the functionality of include. During program execution, the specified file is included. If the program referenced from the file has been included previously, include_once() will not include it again. That is to say, the same file can only be referenced once!
The include_once() statement includes and runs the specified file during script execution. This behavior is similar to the include() statement, the only difference is that if the code in the file is already included, it will not be included again. As the name of this statement implies, it will only be included once.
include_once() should be used when the same file may be included more than once during script execution, and you want to ensure that it is only included once to avoid problems such as function redefinition and variable reassignment.
For more examples of using require_once() and include_once(), see the PEAR code in the latest PHP source program distribution package.
The return value is the same as include(). If the file is included, this function returns TRUE.
Note: include_once() is newly added in PHP 4.0.1pl2.
Note: Be aware that the behavior of include_once() and require_once() in case-insensitive operating systems (such as Windows)
may not be expected.
Example: include_once() is not case sensitive under Windows
include_once("a.php"); // this will include a.php
include_once( "A.php"); // this will include a.php again on Windows! (PHP 4 only)
?>
This behavior was changed in PHP 5, the path is normalized first , so the implementation of C:PROGRA~1A.php and C:Program Filesa.php are the same, and the file will only be included once.
If the file to be included does not exist, include prompts notice, and then continues to execute the following statement, require prompts a fatal error and exits.
Under the win32 platform, they are included first and then executed, so it is best not to have include or require statements in the included files, which will cause directory confusion. Maybe the situation is different under Linux, I haven't tested it yet.
If a file does not want to be included multiple times, you can use include_once or require_once## to read and write document data.
function r($file_name) {
$filenum=@fopen($file_name,"r");
@flock($filenum,LOCK_SH);
$ file_data=@fread($filenum,filesize($file_name));
@fclose($filenum);
return $file_data;
}
function w($file_name,$data,$method ="w"){
$filenum=@fopen($file_name,$method);
flock($filenum,LOCK_EX);
$file_data=fwrite($filenum,$data);
fclose($filenum);
return $file_data;
}
?>