require、include、require_once 和 include_once 之间的区别?

发布于 2024-08-24 10:09:49 字数 163 浏览 6 评论 0 原文

在 PHP 中:

  • 什么时候应该使用 requireinclude
  • 什么时候应该使用 require_onceinclude_once

In PHP:

  • When should I use require vs. include?
  • When should I use require_once vs. include_once?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(28

遗弃M 2024-08-31 10:09:49

还有 requireinclude_once

所以你的问题应该是......

  1. 我什么时候应该使用 requireinclude
  2. 我什么时候应该使用 require_oncerequire

1 的答案已描述 这里

require() 函数与 include() 相同,只是处理错误的方式不同。如果发生错误,include() 函数会生成警告,但脚本将继续执行。 require() 生成致命错误,脚本将停止。

2 的答案可以在此处找到。

require_once() 语句与 require() 相同,只是 PHP 会检查该文件是否已被包含,如果是,则不再包含(require)它。

请注意,现在 *_once 变体几乎没有用处。如果您正在使用它们,这可能是一种盲目的习惯,或者您的代码需要重组。

There are require and include_once as well.

So your question should be...

  1. When should I use require vs. include?
  2. When should I use require_once vs. require

The answer to 1 is described here.

The require() function is identical to include(), except that it handles errors differently. If an error occurs, the include() function generates a warning, but the script will continue execution. The require() generates a fatal error, and the script will stop.

The answer to 2 can be found here.

The require_once() statement is identical to require() except PHP will check if the file has already been included, and if so, not include (require) it again.

Note that nowadays there is little use for *_once variants. If you are using them, it's likely either a mindless habit or your code needs to be restructured.

夏日落 2024-08-31 10:09:49

使用

  • require
    当您的应用程序需要该文件时,例如重要的消息模板或包含配置变量的文件,如果没有这些文件,应用程序就会崩溃。

  • require_once
    当文件包含会在后续包含时产生错误的内容时,例如
    function important() { /* important code */} 在您的应用程序中肯定需要,但由于函数无法重新声明,因此不应再次包含。

  • 包含
    当不需要文件并且应用程序流程在未找到时应继续时,例如
    非常适合引用当前范围内的变量或其他内容的模板

  • include_once
    可选的依赖项会在后续加载时产生错误,或者可能会导致远程文件包含错误,由于 HTTP 开销,您不希望发生两次错误

但基本上,何时使用哪个取决于您。

Use

  • require
    when the file is required by your application, e.g. an important message template or a file containing configuration variables without which the app would break.

  • require_once
    when the file contains content that would produce an error on subsequent inclusion, e.g.
    function important() { /* important code */} is definitely needed in your application but since functions cannot be redeclared should not be included again.

  • include
    when the file is not required and application flow should continue when not found, e.g.
    great for templates referencing variables from the current scope or something

  • include_once
    optional dependencies that would produce errors on subsequent loading or maybe remote file inclusion that you do not want to happen twice due to the HTTP overhead

But basically, it's up to you when to use which.

鱼窥荷 2024-08-31 10:09:49

我的建议是 99.9% 的时间只使用 require_once

使用 requireinclude 意味着您的代码在其他地方不可重用,即您拉入的脚本实际上是执行代码,而不是可用一个类或一些函数库。

如果您需要/包括当场执行的代码,那就是过程代码,您需要了解新的范例。就像面向对象的编程、基于函数的编程或函数式编程。

如果您已经在进行面向对象或函数式编程,那么使用 include_once 基本上会延迟您在堆栈中发现错误/错误的位置。您是否想知道函数 do_cool_stuff() 在您稍后调用它时不可用,或者通过要求 您希望它可用的那一刻图书馆?一般来说,最好立即知道您需要和期望的东西是否不可用,因此只需使用 require_once 即可。

或者,在现代 OOP 中,只需在使用时自动加载您的类。

My suggestion is to just use require_once 99.9% of the time.

Using require or include instead implies that your code is not reusable elsewhere, i.e. that the scripts you're pulling in actually execute code instead of making available a class or some function libraries.

If you are require/including code that executes on the spot, that's procedural code, and you need to get to know a new paradigm. Like object oriented programming, function-based programming, or functional programming.

If you're already doing OO or functional programming, using include_once is mostly going to be delaying where in the stack you find bugs/errors. Do you want to know that the function do_cool_stuff() is not available when you go to call for it later, or the moment that you expect it to be available by requiring the library? Generally, it's best to know immediately if something you need and expect isn't available, so just use require_once.

Alternatively, in modern OOP, just autoload your classes upon use.

夜唯美灬不弃 2024-08-31 10:09:49

带 _once 函数和不带 _once 函数的区别:
没有 _once 的代码将再次被包含,而使用 _once 函数的 PHP 会跟踪包含的文件并且只会包含它一次。

require 和 include 之间的区别:
如果未找到所需的文件,PHP 将发出致命错误,而对于 include 仅发出警告。

Difference between _once functions and without _once functions:
without _once code will be included again whereas with _once functions PHP keeps track of the included files and will include it only once.

Difference between require and include:
If a required file is not found PHP will emit a fatal error whereas for include only a warning will be emitted.

寒尘 2024-08-31 10:09:49

如果 include() 无法包含该文件,则会抛出警告,但脚本的其余部分将运行。

如果脚本无法包含该文件,require() 将抛出 E_COMPILE_ERROR 并停止脚本。

如果已经包含该文件,则 include_once()require_once() 函数不会再次包含该文件。

请参阅以下文档页面:

include() will throw a warning if it can't include the file, but the rest of the script will run.

require() will throw an E_COMPILE_ERROR and halt the script if it can't include the file.

The include_once() and require_once() functions will not include the file a second time if it has already been included.

See the following documentation pages:

人│生佛魔见 2024-08-31 10:09:49

您应该将类​​和函数定义组织在文件中。

使用 require_once() 加载依赖项(类、函数、常量)。

使用 require() 加载类似模板的文件

使用 include_once() 加载可选依赖项(类、函数、常量)。

使用 include() 加载可选的类似模板的文件

You should keep class and function definitions organized in files.

Use require_once() to load dependencies (classes, functions, constants).

Use require() to load template-like files.

Use include_once() to load optional dependencies (classes, functions, constants).

Use include() to load optional template-like files.

浅语花开 2024-08-31 10:09:49

2018年7年后的答案

这个问题是七年前提出的,并且没有一个答案对该问题提供实际帮助。在现代 PHP 编程中,您主要只使用一次 require_once 来包含您的自动加载器类(通常为 Composer 自动加载器),它将加载您的所有类和函数(函数文件需要显式添加到 < code>composer.json 文件可在所有其他文件中使用)。如果您的类无法从自动加载器加载,您可以使用 require_once 来加载它。

有些场合我们需要使用require。例如,如果您有一个非常大的数组定义,并且不想将其添加到类定义源代码中,您可以:

 <?php
// arry.php
return ['x'=>'y'];

 <?php
//main.php
$arr= require 'arry.php'

如果您打算包含的文件包含可执行文件或声明一些变量,则几乎总是需要使用 require,因为如果你除了第一个地方使用 require_once ,你的代码将不会被执行和/或你的变量不会默默地启动,从而导致绝对难以修复的错误查明。

includeinclude_once 确实没有实际用例。

An answer after 7 years for 2018

This question was asked seven years ago, and none of the answers provided practical help for the question. In modern PHP programming, you mainly use require_once only once to include your autoloader class (composer autoloader often), and it will load all of your classes and functions (functions files need to be explicitly added to the composer.json file to be available in all other files). If your class is not loadable from autoloader you use require_once to load it.

There are some occasions that we need to use require. For example, if you have a really big array definition and you don't want to add this to your class definition source code you can:

 <?php
// arry.php
return ['x'=>'y'];

 <?php
//main.php
$arr= require 'arry.php'

If the file that you intend to include contains something executable or declares some variables, you almost always need to use require, because if you use require_once apart from the first place your code will not be executed and/or your variables will not initiate silently, causing bugs that are absolutely hard to pinpoint.

There is no practical use case for include and include_once really.

别挽留 2024-08-31 10:09:49

每当您使用 require_once() 时,当您在当前文件中仅需要一次调用的文件时,可以在文件中使用 require_once() 来包含另一个文件。
在示例中我有一个 test1.php。

<?php  
echo "today is:".date("Y-m-d");  
?>  

在另一个我命名为 test2.php 的文件中,

<?php  
require_once('test1.php');  
require_once('test1.php');  
?>

您正在观看 m 两次需要 test1 文件,但该文件将包含 test1 一次,并且在第二次调用时,这将被忽略。并且无需停止就会显示一次输出。

每当您使用“include_once()”时,当您在当前文件中多次需要调用的文件时,可以在文件中使用“include_once()”来包含另一个文件。
在示例中,我有一个名为 test3.php 的文件。

<?php  
echo "today is:".date("Y-m-d");  
?> 

在我命名为 test4.php 的另一个文件中,

<?php  
include_once('test3.php');  
include_once('test3.php');  
?>

当您正在观看包含 test3 文件的 m 时,将包含该文件一次,但会停止进一步执行。

Whenever you are using require_once() can be use in a file to include another file when you need the called file only a single time in the current file.
Here in the example I have an test1.php.

<?php  
echo "today is:".date("Y-m-d");  
?>  

and in another file that I have named test2.php

<?php  
require_once('test1.php');  
require_once('test1.php');  
?>

as you are watching the m requiring the the test1 file twice but the file will include the test1 once and for calling at the second time this will be ignored. And without halting will display the output a single time.

Whenever you are using 'include_once()` can be used in a file to include another file when you need the called file more than once in the current file.
Here in the example I have a file named test3.php.

<?php  
echo "today is:".date("Y-m-d");  
?> 

And in another file that I have named test4.php

<?php  
include_once('test3.php');  
include_once('test3.php');  
?>

as you are watching the m including the test3 file will include the file a single time but halt the further execution.

剧终人散尽 2024-08-31 10:09:49

对可重用的 PHP 模板使用“include”。对所需的库使用“require”。

“*_once”很好,因为它检查文件是否已经加载,但它只对我在“require_once”中有意义。

Use "include" for reusable PHP templates. Use "require" for required libraries.

"*_once" is nice, because it checks whether the file is already loaded or not, but it only makes sense for me in "require_once".

眼前雾蒙蒙 2024-08-31 10:09:49

区别在于命令生成的错误。使用require,您想要使用的文件确实是必需的,因此如果未找到该文件,则会生成E_ERROR

require()include() 相同,但失败时也会产生致命的 E_ERROR 级别错误。

include 仅在失败时生成 E_WARNING 错误,该错误或多或少是无声的。

因此,如果需要该文件才能使其余代码正常工作,并且您希望脚本失败且文件不可用,请使用它。


对于*_once()

include_once() 可用于在脚本的特定执行期间可能多次包含和评估同一文件的情况,因此在这种情况下,它可能有助于避免诸如函数之类的问题重新定义、变量值重新分配等

当然,这同样适用于 require_once()


参考:require()include_once()

The difference is in the error the commands generate. With require, the file you want to use is really required and thus generates an E_ERROR if it is not found.

require() is identical to include() except upon failure it will also produce a fatal E_ERROR level error.

include only generates an E_WARNING error if it fails which is more or less silent.

So use it if the file is required to make the remaining code work and you want the script to fail the file is not available.


For *_once():

include_once() may be used in cases where the same file might be included and evaluated more than once during a particular execution of a script, so in this case it may help avoid problems such as function redefinitions, variable value reassignments, etc.

Same applies to require_once() of course.


Reference: require(), include_once()

血之狂魔 2024-08-31 10:09:49

 

  1. 什么时候应该使用requireinclude

    requireinclude 函数执行相同的任务,即包含并评估指定的文件,但不同的是 require 会导致当指定的文件位置无效或出现任何错误时会出现致命错误,而 include 将生成警告并继续执行代码。

    因此,如果您尝试包含的文件是系统的核心,并且可能会对其余部分造成巨大影响,则可以使用require函数当您尝试包含的文件是包含一些不太重要的代码的简单文件时,您可以使用 include 函数。

    我个人的建议(对于不太重要的代码)是在开发阶段的代码中到处使用 require 函数,这样您就可以调试代码,然后替换所有 include 函数>require 函数,这样,如果您错过任何错误,它不会影响最终用户,并且代码的其余部分可以正确执行...

  2. 何时应该使用 require_oncerequire

    requirerequire_once 之间的基本区别是 require_once 会检查文件是否已经包含,如果已经包含则它不会包含该文件,而 require 函数将包含该文件,无论文件是否已包含。

    因此,如果您想一次又一次地包含某些代码片段,请使用 require 函数,而如果您只想在代码中包含某些代码一次,请使用 require_once code>.

 

  1. When should one use require or include?

    The require and include functions do the same task, i.e. includes and evaluates the specified file, but the difference is require will cause a fatal error when the specified file location is invalid or for any error whereas include will generate a warning and continue the code execution.

    So you may use the require function in the case where the file you are trying to include is the heart of the system and may cause a huge impact on rest of the code and you can use the include function when the file you are trying to include is a simple file containing some less important code.

    And my personal recommendation (for less important code) is to go for the require function everywhere in your code while it is in development phase such that you can debug code and later on replace all require functions by include function before moving it to production such that if you miss any bugs it will not affect the end user and the rest of the code executes properly...

  2. When should one use require_once or require?

    The basic difference between require and require_once is require_once will check whether the file is already included or not if it is already included then it won't include the file whereas the require function will include the file irrespective of whether file is already included or not.

    So in cases where you want to include some piece of code again and again use the require function whereas if you want to include some code only once in your code, use require_once.

梦归所梦 2024-08-31 10:09:49

1 - 如果文件不存在,“require”和“require_once”会抛出致命错误
现有并停止脚本执行

2 - “include”和“include_once”抛出警告并执行
继续

3 - 正如其名称所示,“require_once”和“include_once”,
如果该文件已包含在其中,则他们不会包含该文件
“需要”、“require_once”、“包含”或“include_once”

1 - "require" and "require_once" throw a fatal error if the file is not
existing and stop the script execution

2 - "include" and "include_once" throw a warning and the execution
continues

3 - "require_once" and "include_once" as their names suggests ,
they will not include the file if the file was already included with
"require", "require_once", "include" or "include_once"

黒涩兲箜 2024-08-31 10:09:49

要求文件必须存在,如果不存在,则会显示错误;而使用 include - 如果文件不存在,则页面将继续加载。

With require the file must exist, if it doesn't then an error will display; whereas with include - if the file doesn't exist then then the page will continue loading.

明月夜 2024-08-31 10:09:49

需要关键部分,例如授权并包括所有其他部分。

多重包含是非常糟糕的设计,必须完全避免。所以, *_once 并不重要。

Require critical parts, like authorization and include all others.

Multiple includes are just very bad design and must be avoided at all. So, *_once doesn't really matter.

蓝天 2024-08-31 10:09:49

包含 / 需要< /a> 您也可以多次包含同一文件:

require() 与 include() 相同,但失败时也会产生致命的 E_COMPILE_ERROR 级别错误。换句话说,它将停止脚本,而 include() 仅发出警告 (E_WARNING),允许脚本继续。

require_once / include_once< /a>

与 include/require 相同,只是 PHP 会检查该文件是否已被包含,如果是,则不再包含(require)它。

Include / Require you can include the same file more than once also:

require() is identical to include() except upon failure it will also produce a fatal E_COMPILE_ERROR level error. In other words, it will halt the script whereas include() only emits a warning (E_WARNING) which allows the script to continue.

require_once / include_once

is identical to include/require except PHP will check if the file has already been included, and if so, not include (require) it again.

暖树树初阳… 2024-08-31 10:09:49

我使用的函数如下:

function doSomething() {
    require_once(xyz.php);
    ....
}

xyz.php 中声明了常量值。

我必须从另一个 PHP 脚本文件调用这个 doSomething() 函数。

但是我在循环中调用此函数时观察到行为,第一次迭代 doSomething() 在 xyz.php 中获取常量值,但后来每次迭代 doSomething() 都没有获取常量值能够获取xyz.php中声明的常量值。

我通过从 require_once() 切换到 include() 解决了我的问题,更新的 doSomething() 代码如下:

function doSomething() {
    include(xyz.php);
    ....
}

现在每次迭代调用doSomething() 获取在 xyz.php 中定义的常量值。

I was using function as below:

function doSomething() {
    require_once(xyz.php);
    ....
}

There were constant values declared in xyz.php.

I have to call this doSomething() function from another PHP script file.

But I observed behavior while calling this function in a loop, for first iteration doSomething() was getting constant values within xyz.php, but later every iteration doSomething() was not able to get the constant values declared in xyz.php.

I solved my problem by switching from require_once() to include(), updated doSomething() code is as below:

function doSomething() {
    include(xyz.php);
    ....
}

Now every iteration call to doSomething() gets the constant values defined in xyz.php.

等往事风中吹 2024-08-31 10:09:49

来自手册

require()include() 相同,但失败时也会产生致命的 E_COMPILE_ERROR 级别错误。换句话说,它将停止脚本,而 include() 仅发出警告 (E_WARNING),允许脚本继续。

_once() 变体也是如此。

From the manual:

require() is identical to include() except upon failure it will also produce a fatal E_COMPILE_ERROR level error. In other words, it will halt the script whereas include() only emits a warning (E_WARNING) which allows the script to continue.

The same is true for the _once() variants.

绝情姑娘 2024-08-31 10:09:49

include() 在找不到文件时会生成警告,但 require_once() 将生成致命错误。

另一件事是之前是否包含文件。然后 require_once() 将不会再次包含它。

include() will generate a warning when it doesn't find a file, but require_once() will generate a fatal error.

Another thing is if file is included before. Then require_once() will not include it again.

不醒的梦 2024-08-31 10:09:49

在 PSR-0 / PSR-4 自动加载器时代,如果您只需要使某些函数/类可供您的代码使用,则可能完全没有必要使用任何语句(当然,如果您仍然使用 PHP 作为模板引擎,您仍然需要在引导文件中自动加载 require_once 本身并include 模板。

In the age of PSR-0 / PSR-4 autoloaders, it may be completely unnecessary to use any of the statements if all you need is to make some functions / classes available to your code (of course, you still need to require_once autoloader itself in your bootstrap file and include templates if you still use PHP as a template engine).

平生欢 2024-08-31 10:09:49
  1. 或依赖项时,请使用 require 函数。
  2. 当你想加载模板样式的文件时使用include函数

如果你仍然困惑,只需始终使用 require_once 即可。

  1. Use require function when you need to load any class, function, or dependency.

  2. Use include function when you want to load template-styled file

If you are still confused, just use require_once for all time.

仄言 2024-08-31 10:09:49

基本上,如果您需要错误的路径,PHP 会抛出致命错误并调用关闭函数,但是当您包含错误的路径时,PHP 将继续执行,但只会显示文件不存在的警告。

从英文单词 require 可以得知,PHP 页面或文件的执行取决于所需的文件。

根据我的经验,需要重要文件(例​​如配置文件、数据库类和其他重要实用程序)是很正常的。

Basically, if you require a wrong path, PHP throws a fatal error and the shutdown function is called, but when you include a wrong path, PHP will continue execution, but it will just display a warning that the file does not exist.

From the English word require, PHP is told that the execution of the page or file depends on the file required.

From my experience, it's norm to require important files such as configuration files, database classes and other important utilities.

末蓝 2024-08-31 10:09:49

它们都是包含文件的方式。

需要意味着它需要它。 Require_once 意味着它将需要它,但只需要它一次。包含意味着它将包含一个文件,但不需要它才能继续。

示例:

Require 'filename'
Require_once 'filename'
Include 'filename'

还有一个 include_once 函数,它包含一次文件。

Include_once 'filename'

当我用手机打字时,不要使用大写字母。

They are all ways of including files.

Require means it needs it. Require_once means it will need it but only requires it once. Include means it will include a file but it doesn’t need it to continue.

Examples:

Require 'filename'
Require_once 'filename'
Include 'filename'

There is also an include_once function which includes a file once.

Include_once 'filename'

Don’t use capital letters where I have as I am typing from my phone.

风吹雪碎 2024-08-31 10:09:49

我注意到的一件事是,当使用 include 时,我只能从包含它的文件中访问包含的文件函数。使用 require_once,我可以在第二个 required_once 文件中运行该函数。

另外:我建议添加

if(file_exists($RequiredFile)){
    require_once($RequiredFile);
}else{
  die('Error: File Does Not Exist');
}

因为当 require_once 杀死页面时,它有时会回显网站文件的目录

这是我为 require 文件制作的自定义函数:

function addFile($file, $type = 'php', $important=false){
    //site-content is a directory where I store all the files that I plan to require_once
    //the site-content directory has "deny from all" in its .htaccess file to block direct connections
    if($type && file_exists('site-content/'.$file.'.'.$type) && !is_dir('site-content/'.$file.'.'.$type)){
        //!is_dir checks that the file is not a folder
        require_once('site-content/'.$file.'.'.$type);
        return 'site-content/'.$file.'.'.$type;
    }else if(!$type && file_exists('site-content/'.$file) && !is_dir('site-content/'.$file)){
        //if you set "$type=false" you can add the file type (.php, .ect) to the end of the "$file" (useful for requiring files named after changing vars)
        require_once('site-content/'.$file);
        return 'site-content/'.$file;
    }else if($important){
        //if you set $important to true, the function will kill the page (which also prevents accidentally echoing the main directory path of the server)
        die('Server Error: Files Missing');
        return false;
    }else{
        //the function returns false if the file does not exist, so you can check if your functions were successfully added
        return false;
    }
}

用法示例:

$success = addFile('functions/common');

if($success){
    commonFunction();
}else{
    fallbackFunction();
}

one thing I noticed, when using include I can only access the included files functions from the file that included it. With require_once, I can run that function in a second required_once file.

also: I recommend adding

if(file_exists($RequiredFile)){
    require_once($RequiredFile);
}else{
  die('Error: File Does Not Exist');
}

Because when require_once kills the page, it can sometimes echo the directory of your website files

Here's a custom function I made to require files:

function addFile($file, $type = 'php', $important=false){
    //site-content is a directory where I store all the files that I plan to require_once
    //the site-content directory has "deny from all" in its .htaccess file to block direct connections
    if($type && file_exists('site-content/'.$file.'.'.$type) && !is_dir('site-content/'.$file.'.'.$type)){
        //!is_dir checks that the file is not a folder
        require_once('site-content/'.$file.'.'.$type);
        return 'site-content/'.$file.'.'.$type;
    }else if(!$type && file_exists('site-content/'.$file) && !is_dir('site-content/'.$file)){
        //if you set "$type=false" you can add the file type (.php, .ect) to the end of the "$file" (useful for requiring files named after changing vars)
        require_once('site-content/'.$file);
        return 'site-content/'.$file;
    }else if($important){
        //if you set $important to true, the function will kill the page (which also prevents accidentally echoing the main directory path of the server)
        die('Server Error: Files Missing');
        return false;
    }else{
        //the function returns false if the file does not exist, so you can check if your functions were successfully added
        return false;
    }
}

usage example:

$success = addFile('functions/common');

if($success){
    commonFunction();
}else{
    fallbackFunction();
}
|煩躁 2024-08-31 10:09:49

require 生成致命错误,并在找不到文件时停止下一行执行。

include 生成警告,但在找不到文件时没有停止下一行执行。

require_oncerequire 执行相同的操作,但它会检查文件是否已经加载或不执行。

include_onceinclude 的作用相同,但它会检查文件是否已经加载或不执行。

注意:在脚本的特定执行期间可能多次包含和评估同一文件的情况下,可以使用 include_oncerequire_once ,因此在这种情况下可能会有助于避免函数重定义、变量值重新赋值等问题。

require generate fatal error with stopping next line execution while file not found.

include generate warning but did not stop next line execution while file not found.

require_once do the same as require do but it will check if the file has already been loaded or not to be executed.

include_once do the same as include do but it will check if the file has already been loaded or not to be executed.

Note: include_once or require_once may be used in cases where the same file might be included and evaluated more than once during a particular execution of a script, so in this case it may help avoid problems such as function redefinitions, variable value reassignments, etc.

终止放荡 2024-08-31 10:09:49

在 PHP 中,有 4 个类似的函数用于包含和请求文件:

include()include() 语句用于将一个文件的内容包含到另一个文件中。如果找不到包含的文件,将生成警告,但脚本将继续执行。

require()require() 语句与 include 类似,但如果找不到文件,它会生成致命错误。该脚本将立即停止执行。

include_once()include_once() 语句与 include 相同,但它只会包含文件一次,即使在同一脚本中包含多次。

require_once()require_once() 语句与 require 相同,但它只会包含该文件一次,即使它在同一脚本中包含多次。

简单来说:

当您想要包含文件并继续执行脚本(即使文件丢失)时,请使用 include()

当您需要包含文件并在文件丢失时停止执行脚本时,请使用 require()

当您只想包含一个文件一次以避免重复函数或变量出现任何问题时,请使用 include_once()require_once()

注意:一般情况下,建议使用 require_once() 而不是 include_once() 以确保所需文件包含且不丢失。

In PHP, there are 4 similar functions for including and requiring files:

include(): The include() statement is used to include the contents of a file into another file. If the file being included cannot be found, a warning will be generated but the script will continue to execute.

require(): The require() statement is similar to include, but it generates a fatal error if the file cannot be found. The script will stop executing immediately.

include_once(): The include_once() statement is the same as include, but it will only include the file once, even if it is included multiple times in the same script.

require_once(): The require_once() statement is the same as require, but it will only include the file once, even if it is included multiple times in the same script.

In simple terms:

Use include() when you want to include a file and continue executing the script even if the file is missing.

Use require() when you need to include a file and stop executing the script if the file is missing.

Use include_once() or require_once() when you want to include a file only once to avoid any issues with duplicate functions or variables.

Note: In general, it is recommended to use require_once() over include_once() to ensure that the required file is included and not missing.

欲拥i 2024-08-31 10:09:49

这通常是一个问题,您是否想要有条件地加载客户端库,或者无论您是否要使用它,都继续加载它。

这是具体的例子;详细阐述 pcj 所说的话。

假设您有一个存储数据库用户名和密码的配置文件(conf.php):

<?php
//my site configuration file

//For Database
$location='localhost';
$dbuser='yourname';
$userpw='yourpassword';
$database='nameofdatabase';
?>

以及一个具有使用数据库的静态函数的类:

<?php
class UsedInLoop {
    public static function databaseQuery(){
        require(/path/to/conf.php);                //require_once will not work here
        $db = new mysqli($location, $dbuser, $userpw, $database);
        //yada yada yada
    }
}
?>

并且该静态函数在循环内迭代调用的另一个函数内部使用:

<?php
require_once('path/to/arbitraryObject.php');  //either will likely be OK at this level
$obj = new arbitraryObject();
foreach($array as $element){
    $obj->myFunction();
}
?>

您只能要求/包含该类一次。如果您在循环的每次迭代中都需要/包含它,则会收到错误。但是,每次调用静态函数时都必须包含conf 文件。

<?php
class arbitraryObject {
    public function myFunction(){
        require_once(/path/to/UsedInLoop.php);   //This must be require_once. require() will not work
        UsedInLoop::databaseQuery();
    }
}
?>

当然,将其移到函数之外可能是该问题的解决方案:

<?php
require(/path/to/UsedInLoop.php);   //now require() is fine   
class arbitraryObject {
    public function myFunction(){
        UsedInLoop::databaseQuery();
    }
}
?>

除非您担心加载可能仅在某些条件下使用的类的开销,并且不想在不使用时加载它。

It's often a matter of whether you want to load a client library conditionally, or go ahead and load it whether or not you're going to use it.

Here's concrete example; elaborating on what pcj said.

Say you have a configuration file storing your database username and password (conf.php):

<?php
//my site configuration file

//For Database
$location='localhost';
$dbuser='yourname';
$userpw='yourpassword';
$database='nameofdatabase';
?>

And a class with a static function that uses the database:

<?php
class UsedInLoop {
    public static function databaseQuery(){
        require(/path/to/conf.php);                //require_once will not work here
        $db = new mysqli($location, $dbuser, $userpw, $database);
        //yada yada yada
    }
}
?>

And that static function is used inside of another function that is being called iteratively inside a loop:

<?php
require_once('path/to/arbitraryObject.php');  //either will likely be OK at this level
$obj = new arbitraryObject();
foreach($array as $element){
    $obj->myFunction();
}
?>

You can only require/include the class once. If you require/include it on every iteration of your loop, you'll get an error. However, you have to include your conf file every time the static function is called.

<?php
class arbitraryObject {
    public function myFunction(){
        require_once(/path/to/UsedInLoop.php);   //This must be require_once. require() will not work
        UsedInLoop::databaseQuery();
    }
}
?>

Of course, moving it outside of the function could be a solution to that problem:

<?php
require(/path/to/UsedInLoop.php);   //now require() is fine   
class arbitraryObject {
    public function myFunction(){
        UsedInLoop::databaseQuery();
    }
}
?>

Unless you're concerned with the overhead of loading a class that might only be used in certain conditions and don't want to load it when it isn't.

羁客 2024-08-31 10:09:49

require 的开销比 include 更大,因为它必须首先解析文件。将 requires 替换为 includes 通常是一种很好的优化技术。

require has greater overhead than include, since it has to parse the file first. Replacing requires with includes is often a good optimization technique.

执手闯天涯 2024-08-31 10:09:49

只需使用 require 和 include 即可。

因为思考如何使用 include_once 或 require_once 。
即寻找保存包含或所需 PHP 文件的日志数据。
所以这比 include 和 require 慢。

if (!defined(php)) {
    include 'php';
    define(php, 1);
}

就这样使用...

Just use require and include.

Because think how to work with include_once or require_once.
That is looking for log data which save included or required PHP files.
So that is slower than include and require.

if (!defined(php)) {
    include 'php';
    define(php, 1);
}

Just using like this...

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文