Home Backend Development PHP Tutorial A brief analysis of the difference between include and require in PHP

A brief analysis of the difference between include and require in PHP

Jul 18, 2018 am 10:42 AM

This article shares with you the difference between the include and require file functions in PHP. Friends in need can refer to it.

For example, the following code:

include('hello.php');
echo 'include test final!';//include报错,但是会继续执行,显示:include test final!
require('hello.php');
echo 'require test final!';//require报错,停止代码的执行。
Copy after login

One sentence summary:
1.include() generates a warning
2.require() results in a fatal error

In other words, if you want to stop processing the page when the file is missing, don't hesitate to use require(). This is not the case with include() and the script will continue to run. Also make sure the appropriate include_path is set.
That is to say, the required file is read when the program is parsed again, instead of after parsing, if the required file cannot be read, the next step cannot be taken. Therefore, if the file is not included correctly and will cause the program to be included, it is better to use require. It may be slightly more efficient.

Note: require() will include files anyway, while include() can selectively include:

<?php
 if(FALSE){
   require(&#39;x.php&#39;);
 }
 if(FALSE){
   include(&#39;s.php&#39;);
 }
?>
Copy after login

In the above code: x.php will definitely be included, and s. php will definitely not be included.

The two methods provide different usage flexibility:
require is used such as require("MyRequireFile.php");. This function is usually placed at the front of the PHP program. Before the PHP program is executed, it will first read the file specified by require and make it a part of the PHP program web page.
include uses methods such as include("MyIncludeFile.php");. This function is usually placed in the processing section of flow control. The PHP program web page reads the include file when it reads it. In this way, the process of program execution can be simplified.
1. Usage syntax and introduction

1. include()
Syntax: include(/path/to/filename)
include The () statement will include a file at the location where it is called. Including a file has the effect of copying the specified file's data at the location of the statement.
You can ignore the parentheses when using include().

The include() statement can be executed based on conditions. There is a strange phenomenon when using include() in a conditional statement. It must be surrounded by statement block braces or other statement brackets.

2. include_once()
Syntax: include_once(filename)

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 include_once() will first determine whether the file has been included before. If it has been included, it will ignore this inclusion.
include_once() should be used when you want to ensure that it is only included once to avoid problems such as function redefinition and variable reassignment.

Summary: The include_once() function has the same function as include, but it will first verify whether the file has been included. If it is already included, include_once will no longer be executed. Otherwise, the file must be included. It's exactly the same as include except this.

3. require()
Syntax: require(filename)
require() is largely the same as include, both include a template file into require Call sitting position.
There are two important differences between require and include. First, regardless of the location of require, the specification file will be included in the script where require occurs. For example, even if require is placed in an if statement that evaluates to false, the specified file will still be included.
The second important difference is: when require fails, the script will stop running, while in the case of include, the script will continue to execute.

4. require_once()
Syntax: require_once(filename)
require_once() statement includes and runs the specified file during script execution. This behavior is similar to the require() statement. The only difference is that require_once() will first determine whether the file has been included before. If it has been included, it will ignore this inclusion.
require_once() should be used when you want to ensure that it is only included once to avoid problems such as function redefinition and variable reassignment.

Summary: As the website grows larger, some files may be included repeatedly. This may not be a problem, but if you modify the variables of the included file, they will be overwritten because the original file is included again later, which may not be desired. Another problem that can arise is conflicting function names in included files. These problems can be solved using require_once.
require_once function ensures that the file is included only once. After encountering require_once, subsequent attempts to include the same file will be ignored.

2. Summary of differences

1. The difference between include() and require() statements.
The difference between the two: These two structures are exactly the same except how to handle failure.
include() generates a warning and the script continues.
require() will result in a fatal error and the script will stop running.

In other words, use require() if you want to stop processing the page when a missing file or error is encountered. If you want to continue processing the page when an error is encountered, use include().
Note that before PHP 4.3.5, syntax errors in include files did not cause the program to stop, but from this version onwards they will.

2. The difference between include_once(), require_once() and include(), require()
include_once() is the same as require_once() and should be used when the same file may be included more than once during script execution. In this case, you want to ensure that it is only included once to avoid problems such as function redefinition, variable reassignment, etc. This is the main difference between include_once() and require_once() and include() and require().

3. Issues that need attention

1. Path issues
Especially when nested includes, you must pay attention to the included files path of.
For example, file A contains file B, file B contains file C, and files A, B, and C are not in the same folder. It is often easy to make mistakes at this time.
Solution: You can use the dirname(__FILE__) statement, which means to get the absolute path of the current script. Such as: require_once(dirname(__FILE__).'/config.php');

2. Efficiency issues
include_once(), require_once(), and include(), require () is less efficient because they at least have to first determine whether the file is included. This problem has been greatly improved in the PHP5 version, but there is still a difference in efficiency.

Related recommendations:

The usage scenarios and differences of include_once, require_once, and include and require in php.

The difference between include and require in PHP, phpincluderequire

The above is the detailed content of A brief analysis of the difference between include and require in PHP. For more information, please follow other related articles on the PHP Chinese website!

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

Explain the concept of late static binding in PHP. Explain the concept of late static binding in PHP. Mar 21, 2025 pm 01:33 PM

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

See all articles