php如何实现include_once

(*-*)浩
(*-*)浩 原创
2023-02-25 09:32:01 2724浏览

include_once 语句在脚本执行期间包含并运行指定文件。此行为和 include 语句类似,唯一区别是如果该文件中已经被包含过,则不会再次包含。如同此语句名字暗示的那样,只会包含一次。

include_once 可以用于在脚本执行期间同一个文件有可能被包含超过一次的情况下,想确保它只被包含一次以避免函数重定义,变量重新赋值等问题。

Note:(推荐学习:PHP编程从入门到精通

在 PHP 4中,_once 的行为在不区分大小写字母的操作系统(例如 Windows)中有所不同,例如:

include_once 在 PHP 4 运行于不区分大小写的操作系统中

<?php
include_once "a.php"; // 这将包含 a.php
include_once "A.php"; // 这将再次包含 a.php!(仅 PHP 4)
?>

此行为在 PHP 5 中改了,例如在 Windows 中路径先被规格化,因此 C:\PROGRA~1\A.php 和 C:\Program Files\a.php 的实现一样,文件只会被包含一次。

include和include_once:

include载入的文件不会判断是否重复,只要有include语句,就会载入一次(即使可能出现重复载入)。

而include_once载入文件时会有内部判断机制判断前面代码是否已经载入过。

这里需要注意的是include_once是根据前面有无引入相同路径的文件为判断的,而不是根据文件中的内容(即两个待引入的文件内容相同,使用include_once还是会引入两个)。

//test1.php
<?php
include './test2.php';
echo 'this is test1';
include './test2.php';
?>

//test2.php
<?php
echo 'this is test2';
?>

//结果:
this is test2this is test1this is test2


//test1.php
<?php
include './test2.php';
echo 'this is test1';
include_once './test2.php';
?>

//test2.php
<?php
echo 'this is test2';
?>

//结果:
this is test2this is test1


//test1.php
<?php
include_once './test2.php';
echo 'this is test1';
include './test2.php';
?>

//test2.php
<?php
echo 'this is test2';
?>

//结果:
this is test2this is test1this is test2


//test1.php
<?php
include_once './test2.php';
echo 'this is test1';
include_once './test2.php';
?>

//test2.php
<?php
echo 'this is test2';
?>

//结果:
this is test2this is test1

以上就是php如何实现include_once的详细内容,更多请关注php中文网其它相关文章!

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。