Home Backend Development PHP Tutorial PHP包含文件函数include、include_once、require、require_once区别总结_php实例

PHP包含文件函数include、include_once、require、require_once区别总结_php实例

Jun 07, 2016 pm 05:20 PM
include include_once php require require_once

例如下面的代码:

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

一句话总结:
1.include() 产生一个警告
2.require()  则导致一个致命错误

换句话说,如果你想在丢失文件时停止处理页面,那就别犹豫了,用  require()  吧。include()  就不是这样,脚本会继续运行。同时也要确认设置了合适的include_path。
就是说再解析程序时即读取require的文件,而不是解析后,如果不能读取到被require的文件,就不能进行下一步动作。所以,不被正确包含就会导致程序的文件,用require比较好。可能效率上也略微高点。

注意:require() 无论如何都会包含文件,而include() 可以有选择地包含:

复制代码 代码如下:

 if(FALSE){
   require('x.php');
 }
 if(FALSE){
   include('s.php');
 }
?>

上面的代码中:x.php  一定会被包含,而  s.php  一定不会被包含。

二种方式提供不同的使用弹性:
require 的使用方法如 require("MyRequireFile.php"); 。这个函式通常放在 PHP 程式的最前面,PHP 程式在执行前,就会先读入 require 所指定引入的档案,使它变成 PHP 程式网页的一部份。
include 使用方法如 include("MyIncludeFile.php"); 。这个函式一般是放在流程控制的处理区段中。PHP 程式网页在读到 include 的档案时,才将它读进来。这种方式,可以把程式执行时的流程简单化。


一、使用语法和简介

1、include()
语法:include(/path/to/filename)
include()语句将在其被调用的位置处包含一个文件。包含一个文件与在该语句所在位置复制制定文件的数据具有相同内容的效果。
使用include()时可以忽略括号。

可以根据条件来执行include()语句。在条件语句中使用include()有个怪现象,它必须包围在语句块大括号中,或者用其他语句包围符括起来。

2、include_once()
语法:include_once(filename)

include_once() 语句在脚本执行期间包含并运行指定文件。此行为和 include() 语句类似,唯一区别是include_once()会先判断一下这个文件在之前是否已经被包含过,如已经包含,则忽略本次包含。
include_once() 应该用于嵌套包含的情况下,想确保它只被包含一次以避免函数重定义,变量重新赋值等问题。

小结:include_once()函数的作用与include相同,不过它会首先验证是否已经包含了该文件。如果已经包含,则不再执行include_once。否则,则必须包含该文件。除了这一点与include完全相同。

3、require()
语法:require(filename)
require()在很大程度上与include相同,都是将一个模板文件包含到require调用坐在的位置。
require和include之间有两点重要的区别。首先,无论require的位置如何,制定文件都将包含到出现require的脚本中。例如,即使require放在计算结果为假的if语句中,依然会包含指定文件。
第二个重要的区别是:require出错时,脚本将停止运行,而在使用include的情况下,脚本将继续执行。

4、require_once()
语法:require_once(filename)
require_once() 语句在脚本执行期间包含并运行指定文件。此行为和 require() 语句类似,唯一区别是require_once()会先判断一下这个文件在之前是否已经被包含过,如已经包含,则忽略本次包含。
require_once() 应该用于嵌套包含的情况下,想确保它只被包含一次以避免函数重定义,变量重新赋值等问题。

小结:随着网站越来越大,可能会出现重复包含某些文件。这也许不是问题,但又是修改了所包含文件的变量后,却由于后面再次包含原来的文件而被覆盖,可能不希望出现这种情况。还可能出现另一个问题,即所包含文件中函数名的冲突。使用require_once就可以解决这些问题。
require_once函数确保文件只包含一次。在遇到require_once后,后面再试图包含相同的文件时将被忽略。


二、区别总结

1、include()与require()语句区别。
两者区别:这两种结构除了在如何处理失败之外完全一样。
include() 产生一个警告,脚本会继续运行。
require() 则导致一个致命错误,脚本会停止运行。

换句话说,如果想在遇到丢失文件或遇到错误时停止处理页面就用 require()。如果想在遇到错误时继续处理页面就用 include()。
注意在 PHP 4.3.5 之前,包含文件中的语法错误不会导致程序停止,但从此版本之后会。

2、include_once()、require_once()与include()、require()的区别
include_once()和require_once()一样,应该用于在脚本执行期间同一个文件有可能被包含超过一次的情况下,想确保它只被包含一次以避免函数重定义,变量重新赋值等问题。这就是include_once()和require_once()与include() 和require()的主要区别。


三、需要注意的问题

1.路径问题
特别是嵌套包含的时候,一定得注意包含文件的路径。
比如 A文件包含了B文件,B文件包含了C文件,A,B,C文件都不在同一个文件夹下,这个时候往往很容易出错误。
解决方案:可以使用 dirname(__FILE__) 语句,这句的意思是获得当前脚本的绝对路径。如:require_once(dirname(__FILE__).'/config.php');

2.效率问题
include_once(),require_once(),与include(),require()比较,效率要低一些,因为他们至少得先判断一下这个文件是否已包含。这一问题在PHP5版本有很大改进,不过效率还是有差别。

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 Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
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)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1269
29
C# Tutorial
1249
24
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,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

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.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

See all articles