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.