首頁  >  文章  >  後端開發  >  php如何實作include_once

php如何實作include_once

(*-*)浩
(*-*)浩原創
2019-09-27 13:21:533177瀏覽

include_once 語句在腳本執行期間包含並執行指定檔案。 此行為和 include 語句類似,唯一差異是如果該檔案中已經被包含過,則不會再次包含。如同此語句名字暗示的那樣,只會包含一次。

php如何實作include_once

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 &#39;./test2.php&#39;;
echo &#39;this is test1&#39;;
include &#39;./test2.php&#39;;
?>

//test2.php
<?php
echo &#39;this is test2&#39;;
?>

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


//test1.php
<?php
include &#39;./test2.php&#39;;
echo &#39;this is test1&#39;;
include_once &#39;./test2.php&#39;;
?>

//test2.php
<?php
echo &#39;this is test2&#39;;
?>

//结果:
this is test2this is test1


//test1.php
<?php
include_once &#39;./test2.php&#39;;
echo &#39;this is test1&#39;;
include &#39;./test2.php&#39;;
?>

//test2.php
<?php
echo &#39;this is test2&#39;;
?>

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


//test1.php
<?php
include_once &#39;./test2.php&#39;;
echo &#39;this is test1&#39;;
include_once &#39;./test2.php&#39;;
?>

//test2.php
<?php
echo &#39;this is test2&#39;;
?>

//结果:
this is test2this is test1

以上是php如何實作include_once的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn