PHP require_once 语句

phpserver side programmingprogramming更新于 2025/8/19 12:22:17

简介

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

require_once 语句的其他功能与 require 语句类似。

require_once 示例

以下示例中,主 PHP 脚本包含 test.php

示例

<?php
echo "inside main script
"; echo "now including with require_once test.php script
"; require_once "test.php"; echo "try to include it again"; require_once "test.php"; ?> //test.php <?php echo "File included
"; ?>

输出

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

inside main script
now including with require_once test.php script
File included
try to include it again

require_once 语句失败导致的错误

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

示例

<?php
echo "inside main script
"; echo "now including with require_once notest.php script
"; 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

相关文章