PHP include_once 语句

phpserver side programmingprogramming更新于 2025/7/18 19:07:17

简介

与 include 语句一样,include_once 语句也会将一个文件中编写的脚本传输并执行到另一个文件中。两者的区别在于,include_once 语句会阻止已加载的同一文件再次加载。顾名思义,即使再次尝试执行 include 指令,文件也只会被加载一次。

include_once 语句通常用于设置全局变量、启用库或任何预期在应用程序执行开始时执行的操作。

除此之外,include_once 语句的行为与 include 语句类似。

include_once 示例

以下示例中,testscript.php 位于 Apache 服务器的文档根文件夹中。它使用 include_once 语句插入 test.php

示例

<?php
echo "calling include_once statement
"; $result=include_once "test.php"; ?> //test.php <?php echo "This file is included once
"; ?>

输出

如果提供 testscript.php 的 URL,浏览器中将显示以下结果−

调用 include_once 语句

此文件仅被包含一次

包含失败警告

如果未找到文件参数或 include_once 语句,解析器将发出警告

示例

<?php
echo "inside main script<br />";
$var1=100;
echo "now calling nosuchfile.php script";
include_once "nosuchfile.php";
echo "returns from nosuchfile.php";
?>

输出

这将产生以下结果。请注意,程序不会因警告而终止−

inside main script
now calling nosuchfile.php script
PHP Warning: include_once(nosuchfile.php): failed to open stream: No such file or directory in line 5
PHP Warning: include_once(): Failed opening 'nosuchfile.php' for inclusion (include_path='C:\xampp\php\PEAR') in line 5
returns from nosuchfile.php

再次调用include_once

下一个示例使用include_once语句包含test.php。请注意,不会再次包含同一个文件

示例

//main script
<?php
echo "inside main script<br>";
echo "now including test.php script<br>";
include_once "test.php";
echo "now including again test.php script<br>";
?>
//test.php included
<?php
echo "This file is included once";
?>

输出

这将在浏览器中产生以下结果−

inside main script<br />now including test.php script<br />

此文件已包含一次

现在再次包含 test.php 脚本


相关文章