Home >Backend Development >PHP Tutorial >Detailed explanation of include, include_once and require and require_once statements in PHP

Detailed explanation of include, include_once and require and require_once statements in PHP

黄舟
黄舟Original
2017-06-25 11:14:381548browse

include() and require() statements include and run the specified file. The two structures are exactly the same in include files, the only difference is the handling of errors. When the require() statement encounters that the included file does not exist or an error occurs, it will stop and report an error. include() then continue.

1.include statement

Use the include statement to tell PHP to extract a specific file and load its entire contents


<?php
inlude "fileinfo.php";

//此处添加其他代码
?>

2.include_onceStatement

Every time you use the include statement, it will re-import the requested file, even if this file has been imported. For example, assuming that the fileinfo.php file contains many functions, we use the include statement to import it into an existing file, and then we import a file containing fileinfo.php. Through nesting, we have The fileinfo.php file is imported twice, which generates an error because we are trying to define a variable or function with the same name multiple times. In order to avoid this happening, we use the include_once statement instead of the include statement

<?php
include_once "fileinfo.php";

//此处添加其他代码
?>

At this time, if another include or include_once statement is encountered in the same file, PHP will check whether it has been imported. , if so, ignore it.

3.require and require_once Statements

The potential problem with using include and include_once statements is: PHP will only try Import the requested file. Even if the file is not found, the program will still execute.
When we absolutely need to import a file, we use the require statement. The reason for using the require_once statement is the same, so I won’t go into details here.

<?php
require_once "fileinfo.php";

//此处添加其他代码
?>

In general, we should stick to the require_once statement.

The above is the detailed content of Detailed explanation of include, include_once and require and require_once statements in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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