Differences between require, require_once, include, and include_once in PHP (repost)

Source: Internet
Author: User
Tags flock parse error

 

One of the most common PHP problems mentioned during the interview, I would like to share with you the many similarities and differences between require () and include. Understanding their differences is very important, otherwise it is easy to make mistakes. I will describe these two statements together, So readers can learn more.
1. Require () Statement
The require () statement is used to replace the specified file with the statement itself, just like the include () Statement in C. If the URL fopen wrappers in the PHP configuration file PHP. INI is opened (it is opened by default), you can use the URL to specify the file location to call remote files.
Pay special attention to the use of require () and include () statements. That is, in the contained file, the processor interprets the content in the HTML mode, and restores the content to the PHP mode after processing the included content. Therefore, if you need to use the PHP syntax in the contained file, you need to use the correct PHP start and end mark to include these statements.
Knowledge of require () and include () is a language feature in PHP, rather than a function. They are different from functions.
For example, the file contained in require () cannot contain a control structure, and the return statement cannot be used. Using the return statement in files contained in require () produces processing errors.
Unlike the include () Statement, the require () Statement unconditionally reads the content of the files it contains, regardless of whether these statements are executed. Therefore, if you want to include different files according to different conditions, you must use the include () statement. Of course, if the statement where require () is located is not executed, the statements in the file contained in require () will not be executed.
Require () cannot contain different files in the loop body based on different conditions. The require () Statement will only replace itself with the content in the file it contains when it is executed for the first time. When it is executed again, it can only execute the statements contained for the first time. However, the include () statement can contain different files in the loop body.
The variables in the require () Statement inherit the scope of the variables where the require () Statement is located. All variables that can be accessed at the location of the require () statement can be accessed in the files contained in the require () statement. If the require () Statement is inside a function, all the statements in the contained file are defined inside the function.
The require () statement reads the file referenced by require before the PHP program is executed. Therefore, require is usually placed at the beginning of the program. Therefore, pay special attention to the fact that the require statement is strong. No matter whether the program really needs to reference the file or not, as long as you use the require statement, it will include them! Even if you use this function in a condition control statement to include, the referenced file will be contained even if the condition is not true! The formation of botnets does not have any visible effect during the running process, but it is obvious that it will increase the burden, so pay special attention to this! If an error occurs when you use the require statement, the program outputs the error message and stops running !!

If the require () statement declares the URL of the file to contain the remote file, and the remote server interprets the file according to the PHP code, the content contained in the local PHP file is the result after being processed on the remote server. For example:
/*
In this example, the some_serverserver server can interpret the. php file instead of the. txt file. In a remote file
Variables $ varfirst and $ varsecond are required.
*/
/* The remote server cannot process the. txt file */
Require ("http: // some_server/file.txt? Varfirst = 1 & varsecond = 2 ");

/* Incorrect. You can only search for 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, the return statement can be used for the files contained in require (), but the condition is that the return statement cannot appear inside, it must appear in the global scope of the included files. This feature of require () has been canceled in php4.0, but can still be implemented using include.

2. Include () Statement
The include () and require () statements have many similarities. Unless explicitly stated in the preceding require () Statement, the function of the require () Statement is applicable to include () statements. The following describes the functions and features of the include () statement not available in the require () statement.
The include statement reads the file to be included only when it is executed. The include statement is easy to handle errors. If an include error occurs, the program skips the include statement. Although the error message is displayed, the program continues to execute!
The PHP processor will re-process the include () statement every time it encounters it. Therefore, you can use include () in conditional control statements and loop statements based on different situations () to contain different files.
For example:
<? PHP
$ Files = array ('first. php', 'second. php', 'third. php ');
For ($ I = 0; $ I <count ($ files); $ I ++)
{
Include $ files [$ I];
}
?>
You can use the return statement to return a value in the files contained in the include () Statement in php3.0 and php4.0, and stop executing the content under the included file. However, php3.0 and php4.0 are different in handling such situations. In php3.0, the return statement cannot be included in {} unless it is in a function, because it indicates the return value of the function rather than the return value of the file. In php4.0, users can even return a number in the file, just like the return value of the function. Such a statement

Errors are usually reported in php3.0. The following is an example:
Assume that the contained 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
<? PHP
Echo "before the return <br>/N ";
If (1)
{
Return 27;
}
Echo "after the return <br>/N ";
?>

Assume that the main. php file contains the following statement:
<? PHP
$ Retval = include ('test. inc ');
Echo "file returned: '$ retval' <br>/N ";
?>
The php3.0 interpreter reports an error in the second line, but cannot get the return value of the include () statement. However, the following result is displayed in php4.0:
Before the return
File returned: '27'
Next let's assume that main. php is changed:
<? PHP
Include ('test. inc ');
Echo "back in main.html <br>/N ";
?>
The output result 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
27 back in main.html

Parse error: Parse error in/Apache/htdocs/phptest/main.html on line 5

The above error occurs because the return statement is inside {} and not inside a function. If you remove {} to the outermost layer of test. Inc, the output result is:
Before the return
27 back in main.html
The reason why 27 appears is that include () is not supported in php3.0.

3. require_once () and include_once () Statements
The require_once () and include_once () Statements correspond to the require () and include () statements respectively. The require_once () and include_once () statements are mainly used to avoid repeated function or variable definition errors when you need to include multiple files. For example, if you create two files util. INC and fool. Inc, the program code is:
Util. Inc:
<? PHP
Define (phpversion, floor (phpversion ()));
Echo "globals are nice <br>/N ";
Function goodtea ()
{
Return "olong tea tasts good! ";
}
?>
And fool. Inc:
<? PHP
Require ("util. Inc ");
Function showvar ($ var)
{
If (phpversion = 4)
{
Print_r ($ var );
}
Else
{
Var_dump ($ var );
}
}
?>
Then include the two files in error_require.php:
<? PHP
Require ("Fool. Inc ");
Require ("util. Inc"); // This sentence produces an error
$ Foo = array ("1", array ("complex", "quaternion "));
Echo "this is requiring util. inc again which is also <br>/N ";
Echo "required in fool. INC/N ";
Echo "Running goodtea:". goodtea (). "<br>/N ";
Echo "printing FOO: <br>/N ";
Showvar ($ Foo );
?>
When running error_require.php, the output result 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. Change the require () Statement in error_require.php and fool. Inc to the require_once () Statement and rename it 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 that of the include () statement. The main difference is to avoid repeated definitions of functions or variables caused by multiple inclusion of a file.

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 include function. During program execution, the specified file is included. If the program referenced from the file has previously been included, include_once () will not include it again. That is, you can only reference the same file once!

The include_once () statement contains 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 has been included, it will not be included again. As the statement name implies, it will only be included once.

Include_once () should be used when the same file may be contained more than once during script execution, to ensure that it is only included once to avoid function redefinition, variable re-assignment and other issues.

For more examples of using require_once () and include_once (), see the pear code in the latest PHP source program release package.

The returned value is the same as include. If the file has been included, this function returns true.

Note: include_once () is newly added in PHP 4.0.1pl2.

Note: The behavior of include_once () and require_once () in case-insensitive operating systems (such as Windows) should be noted.

It may not be expected.
Example: include_once () is case insensitive in Windows

<? PHP
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 is changed in PHP 5, and the path is normalized first, so C:/progra ~ 1/A. php and C:/program files/a. php will be included only 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.

On the Win32 platform, they are all included first and then executed. Therefore, it is best not to have include or require statements in the contained files, which will cause directory confusion. It may be different in Linux and has not been tested yet.

If you do not want to include a file multiple times, you can use include_once or require_once # to read the file data.
<? PHP
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;
}

 

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.