发布时间:2025-12-09 12:01:25 浏览次数:10
我们已经在文章PHP | PHP中了解了文件包含在PHP中的知识。 (包括并要求)。我们已经在上一篇文章中讨论了用于文件包含的include()和require()函数。在本文中,我们将讨论PHP中另外两个有用的函数,用于包含文件:include_once()和require_once()函数。
include_once()函数
当您可能需要多次包含被调用的文件时,可以使用include_once()函数将PHP文件包含在另一个文件中。如果发现该文件已被包含,则调用脚本将忽略其他包含。
如果名为a.php的文件是使用include_once()函数调用b.php的php脚本,但未找到b.php,则a.php会执行警告,但不包括b.php中编写的部分代码。
用法:
include_once('name of the called file with path');例:
// name of file is header.inc.php <?php echo "GEEKSFORGEEKS"; ?>上面的文件是header.inc.php
上面的文件header.inc.php被include_once()函数两次包含在以下文件index.php中。但是从输出中,您将获得忽略包含的第二个实例,因为include_once()函数会忽略第一个包含的所有相似包含。
// name of file is index.php <?php include_once('header.inc.php'); include_once('header.inc.php'); ?>输出:
GEEKSFORGEEKS
require_once()函数
当您可能需要多次包含被调用的文件时,可以使用require_once()函数将PHP文件包含在另一个文件中。如果发现该文件已被包含,则调用脚本将忽略其他包含。
如果a.php是使用require_once()函数调用b.php的php脚本,但未找到b.php,则a.php会停止执行,从而导致致命错误。
用法:
require_once('name of the called file with path');例:
// name of file is header.inc.php <?php echo "GEEKSFORGEEKS"; ?>上面的文件是header.inc.php
上面的文件header.inc.php被require_once()函数两次包含在以下文件index.php中。但是从输出中,您将获得忽略包含的第二个实例,因为require_once()函数会忽略第一个包含的所有相似包含。
// name of file is index.php <?php require_once('header.inc.php'); require_once('header.inc.php'); ?>输出:
GEEKSFORGEEKS
include_once()和require_once()
这两个函数的工作原理相同,并产生相同的输出,但是如果出现任何错误,就会产生差异。
例:
如果我们没有名为header.inc.php的文件,则对于include_once(),输出将显示有关文件丢失的警告,但至少输出将从index.php文件显示。
对于require_once(),如果缺少文件PHP文件,则将发生致命错误,并且不会显示任何输出,并且执行将暂停。