PHP require_once语句

介绍

PHP中的 require_once语句在功能上与require语句相似。唯一的区别是,如果已经包含要处理的文件,则不会再次包含该文件。请注意,即使使用了require_once语句,include或require语句包含的文件也不会再次包含。

require_once语句的其他行为类似于require语句。

require_once示例

在下面的示例中,主要的php脚本包括test.php---

示例

<?php
echo "inside main script\n";
echo "now including with require_once test.php--- script\n";
require_once "test.php---";
echo "t再次尝试包含它";
require_once "test.php---";
?>
//test.php---
<?php
echo "File included\n";
?>

输出结果

从命令行运行主脚本时,将产生以下结果:

inside main script
now including with require_once test.php--- script
File included
t再次尝试包含它

失败的require_once错误

尝试添加不存在的文件时,require_once语句也会导致致命错误

示例

<?php
echo "inside main script\n";
echo "now including with require_once notest.php--- script\n";
require_once "notest.php---";
?>

输出结果

这将产生以下结果。请注意,程序因错误而终止-

inside main script
now including with require_once notest.php--- script
PHP Fatal error: require_once(): Failed opening required 'notest.php---' (include_path='C:\xampp\php\PEAR') in line 4
Fatal error: require_once(): Failed opening required 'notest.php---' (include_path='C:\xampp\php\PEAR') in line 4