Home Backend Development PHP Tutorial Similarities and differences between require(), include(), require_once() and include_once()_PHP Tutorial

Similarities and differences between require(), include(), require_once() and include_once()_PHP Tutorial

Jul 21, 2016 pm 03:58 PM
include once require and Similarities and Differences have of resemblance

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;
}
?>

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/317675.htmlTechArticlerequire() and include() have many similarities and some differences. It's important to understand their differences, otherwise it's easy to make mistakes. I introduce these two sentences together, readers can...
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to set up the keyboard boot function on a GIGABYTE motherboard (enable keyboard boot mode on GIGABYTE motherboard) How to set up the keyboard boot function on a GIGABYTE motherboard (enable keyboard boot mode on GIGABYTE motherboard) Dec 31, 2023 pm 05:15 PM

How to set up keyboard startup on Gigabyte's motherboard. First, if it needs to support keyboard startup, it must be a PS2 keyboard! ! The setting steps are as follows: Step 1: Press Del or F2 to enter the BIOS after booting, and go to the Advanced (Advanced) mode of the BIOS. Ordinary motherboards enter the EZ (Easy) mode of the motherboard by default. You need to press F7 to switch to the Advanced mode. ROG series motherboards enter the BIOS by default. Advanced mode (we use Simplified Chinese to demonstrate) Step 2: Select to - [Advanced] - [Advanced Power Management (APM)] Step 3: Find the option [Wake up by PS2 keyboard] Step 4: This option The default is Disabled. After pulling down, you can see three different setting options, namely press [space bar] to turn on the computer, press group

vue3+vite: How to solve the error when using require to dynamically import images in src vue3+vite: How to solve the error when using require to dynamically import images in src May 21, 2023 pm 03:16 PM

vue3+vite:src uses require to dynamically import images and error reports and solutions. vue3+vite dynamically imports multiple images. If vue3 is using typescript development, require will introduce image errors. requireisnotdefined cannot be used like vue2 such as imgUrl:require(' .../assets/test.png') is imported because typescript does not support require, so import is used. Here is how to solve it: use awaitimport

The first choice for CS players: recommended computer configuration The first choice for CS players: recommended computer configuration Jan 02, 2024 pm 04:26 PM

1. Processor When choosing a computer configuration, the processor is one of the most important components. For playing games like CS, the performance of the processor directly affects the smoothness and response speed of the game. It is recommended to choose Intel Core i5 or i7 series processors because they have powerful multi-core processing capabilities and high frequencies, and can easily cope with the high requirements of CS. 2. Graphics card Graphics card is one of the important factors in game performance. For shooting games such as CS, the performance of the graphics card directly affects the clarity and smoothness of the game screen. It is recommended to choose NVIDIA GeForce GTX series or AMD Radeon RX series graphics cards. They have excellent graphics processing capabilities and high frame rate output, and can provide a better gaming experience. 3. Memory power

Digital audio output interface on the motherboard-SPDIF OUT Digital audio output interface on the motherboard-SPDIF OUT Jan 14, 2024 pm 04:42 PM

SPDIFOUT connection line sequence on the motherboard. Recently, I encountered a problem regarding the wiring sequence of the wires. I checked online. Some information says that 1, 2, and 4 correspond to out, +5V, and ground; while other information says that 1, 2, and 4 correspond to out, ground, and +5V. The best way is to check your motherboard manual. If you can't find the manual, you can use a multimeter to measure it. Find the ground first, then you can determine the order of the rest of the wiring. How to connect motherboard VDG wiring When connecting the VDG wiring of the motherboard, you need to plug one end of the VGA cable into the VGA interface of the monitor and the other end into the VGA interface of the computer's graphics card. Please be careful not to plug it into the motherboard's VGA port. Once connected, you can

Glodon Software's computer configuration recommendations; Glodon Software's computer configuration requirements Glodon Software's computer configuration recommendations; Glodon Software's computer configuration requirements Jan 01, 2024 pm 12:52 PM

Glodon Software is a software company focusing on the field of building informatization. Its products are widely used in all aspects of architectural design, construction, and operation. Due to the complex functions and large data volume of Glodon software, it requires high computer configuration. This article will elaborate on the computer configuration recommendations of Glodon Software from many aspects to help readers choose a suitable computer configuration processor. Glodon Software requires a large amount of data calculation and processing when performing architectural design, simulation and other operations. Therefore, the requirements for the processor are higher. It is recommended to choose a multi-core, high-frequency processor, such as Intel i7 series or AMD Ryzen series. These processors have strong computing power and multi-thread processing capabilities, and can better meet the needs of Glodon software. Memory Memory is affecting computing

ASUS motherboard options compatible with R55600 (including R55600u and 5600h) ASUS motherboard options compatible with R55600 (including R55600u and 5600h) Jan 02, 2024 pm 05:32 PM

Which ASUS motherboard should be paired with the R55600? The ASUS ROGStrixB550-FGaming motherboard is an excellent choice. It is perfectly compatible with Ryzen55600X processor and provides excellent performance and features. This motherboard has a reliable power supply system, can support overclocking, and provides a wealth of expansion slots and ports to meet daily use and gaming needs. ROGStrixB550-FGaming is also equipped with high-quality audio solutions, fast network connections and reliable heat dissipation design to ensure that the system remains efficient and stable. In addition, this motherboard adopts a gorgeous ROG style and is equipped with gorgeous RGB lighting effects, adding visual enjoyment to your computer. All in all, ASUS ROGStri

Detailed explanation of the similarities and differences between C language and Python in programming Detailed explanation of the similarities and differences between C language and Python in programming Mar 18, 2024 pm 12:09 PM

C language and Python are two commonly used programming languages, and they have obvious similarities and differences in many aspects. This article will make a detailed comparison between C language and Python in terms of syntax, performance, ease of use, etc., and provide specific code examples to demonstrate the differences between them. Similarities and differences in syntax: C language is a process-oriented programming language. The syntax is relatively rigorous and cumbersome, requiring developers to manage memory and data types by themselves. Python is a high-level language with concise and easy-to-read syntax, and there is no need to explicitly declare variable types. Sample code

What is the difference between php include and include_once What is the difference between php include and include_once Mar 22, 2023 am 10:38 AM

When we write web pages using PHP, sometimes we need to include code from other PHP files in the current PHP file. At this time, you can use the include or include_once function to implement file inclusion. So, what is the difference between include and include_once?

See all articles