PHP require_once 語句


簡介

PHP 中的**require_once** 語句在功能上類似於 require 語句。唯一的區別是,如果某個檔案已經包含在處理中,則不會再次包含該檔案。請注意,即使使用了 require_once 語句,使用 include 或 require 語句包含的檔案也不會再次包含。

require_once 語句的其他行為類似於 require 語句。

require_once 示例

在以下示例中,主 php 指令碼包含 test.php

示例

 即時演示

<?php
echo "inside main script
"; echo "now including with require_once test.php script
"; require_once "test.php"; echo "try to include it again"; require_once "test.php"; ?> //test.php <?php echo "File included
"; ?>

輸出

當從命令列執行主指令碼時,將產生以下結果 −

inside main script
now including with require_once test.php script
File included
try to include it again

failed require_once 的錯誤

在嘗試新增不存在的檔案時,require_once 語句也會導致致命錯誤

示例

 即時演示

<?php
echo "inside main script
"; echo "now including with require_once notest.php script
"; require_once "notest.php"; ?>

輸出

將產生以下結果。請注意,程式在發生錯誤時已終止 −

inside main script
now including with require_once notest.php script
PHP Fatal error: require_once(): Failed opening required 'notest.php' (include_path='C:\xampp\php\PEAR') in line 4
Fatal error: require_once(): Failed opening required 'notest.php' (include_path='C:\xampp\php\PEAR') in line 4

更新於:18-Sep-2020

272 瀏覽量

開啟你的 職業生涯

透過完成課程獲取認證

開始
廣告
© . All rights reserved.