PHP include_once 语句


介绍

与 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,这将在浏览器中产生以下结果:

calling include_once statement

此文件只包含一次

包含失败的警告

如果找不到 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 脚本

更新于:2020年9月18日

248 次浏览

启动您的 职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.