📜  PHP中 require() 和 require_once() 的区别

📅  最后修改于: 2022-05-13 01:56:27.599000             🧑  作者: Mango

PHP中 require() 和 require_once() 的区别

PHP要求()函数: PHP中的 require()函数主要用于将一个PHP文件的代码/数据包含到另一个文件中。在此过程中,如果出现任何类型的错误,则此require()函数将显示警告以及致命错误,这将立即停止脚本的执行。

为了使用这个require()函数,我们首先需要创建两个PHP文件。使用include()函数将一个PHP文件包含到另一个文件中。两个PHP文件合并为一个 HTML 文件。这个require()函数 之前不会查看代码是否包含在指定的文件中,而是会在使用require()函数的次数时包含代码。

例子:

HTML

  

    

Welcome to geeks for geeks!

    

Myself, Gaurav Gandal

       

Thank you

          


requiregfg.php
visit Again-" . date("Y") 
        . " geeks for geeks.com

";    ?>


PHP


demo.php


要求gfg。 PHP

visit Again-" . date("Y") 
        . " geeks for geeks.com

";    ?>

输出:

PHP require_once()函数 PHP中的 require_once ()函数用于将一个PHP文件包含到另一个PHP文件中。它为我们提供了一个功能,如果PHP文件中的代码已经包含在指定文件中,那么如果我们使用require_once()函数,它将不会再次包含该代码。这意味着这个函数只会将一个文件添加到另一个文件中一次。

如果此函数没有找到指定的文件,则会产生致命错误并立即停止执行。

例子:

PHP


上面的PHP代码中使用了以下代码。

演示。 PHP


输出:

require() 和 require_once() 的区别:

                                    require()                                                require_once()
The require() function is used to include a PHP file into another irrespective of whether the file is included before or not.The require_once() will first check whether a file is already included or not and if it is already included then it will not include it again.
This function is mostly used where you want to include a certain code again and again.This function is mostly used where you want to include a certain code just once.
 Use require() to load template-like files.Use require_once() to load dependencies ( classes, functions, constants).
The require() function will execute every time it is called.The require_once() function will not execute every time it is called (It will not execute if the file to be included is included before)