首頁  >  文章  >  後端開發  >  php載入檔案的方法有哪些

php載入檔案的方法有哪些

青灯夜游
青灯夜游原創
2021-05-26 17:51:082481瀏覽

php載入檔案的方法:1、使用「include '檔案名稱'」語句載入;2、使用「require '檔案名稱』」語句載入;3、使用「include_once '檔案名稱』」語句載入;4、使用「require_once '檔名'」語句載入。

php載入檔案的方法有哪些

本教學操作環境:windows7系統、PHP7.1版,DELL G3電腦

PHP中有四個載入檔案的語句: include、require、include_once、require_once

基本語法

require:require函數一般放在PHP腳本的最前面,PHP執行前就會先讀入require指定引入的文件,包含並嘗試執行引入的腳本檔案。 require的工作方式是提高PHP的執行效率,當它在同一個網頁中解釋過一次後,第二次就不會解釋。但同樣的,正因為它不會重複解釋引入文件,所以當PHP中使用循環或條件語句來引入文件時,需要用到include。

include:可以放在PHP腳本的任何位置,一般放在流程控制的處理部分。當PHP腳本執行到include指定引入的檔案時,才將它包含並嘗試執行。這種方式可以把程式執行時的流程簡單化。當第二次遇到相同檔案時,PHP還是會重新解釋一次,include相對於require的執行效率下降很多,同時在引入檔案中包含使用者自訂函數時,PHP在解釋過程中會發生函數重複定義問題。

require_once / include_once:分別與require / include作用相同,不同的是他們在執行到時會先檢查目標內容是不是在之前已經導入過,如果導入過了,那麼便不會再重複引入其同樣的內容。

相互區別

include和require:

    include有回傳值,而require沒有回傳值

    include在載入文件失敗時,會產生一個警告(E_WARNING),在錯誤發生後腳本繼續執行。所以include用在希望繼續執行並向使用者輸出結果時。

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

//test2.php
<?php
echo &#39;this is test2\n&#39;;
function test() {
    echo &#39;this is test\n&#39;;
}
?>

//结果:
this is test1

require在載入失敗時會產生一個致命錯誤(E_COMPILE_ERROR),在錯誤發生後腳本停止執行。一般用在後續程式碼依賴於載入的檔案的時候。

//test1.php
f81d2cd4f815e481087b9c80f83aa3eb

//test2.php
b7986a3ae952129a88602dc298100a68

結果:

#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

require和require_once:同include和include_once的差別相同。

載入時執行程序

1. 從include(require)語句退出php腳本模式(進入html程式碼模式)

2. 載入入include語句所設定的檔案中的程式碼,並嘗試執行

3. 退出html模式,重新進入php腳本模式,繼續後面腳本程式的執行

//test1.php
<html>
<body>
主文件开始位置:
<?php
    echo "<br> 主文件中位置 A";
    include "./test2.php";    //要载入的文件
    echo "<br> 主文件中位置 B";
?>
<br> 主文件结束位置
</body>
</html>

//test2.php
<br> 被载入文件位置 1
<?php
echo "<br> 被载入文件位置 2";
?>
<br> 被载入文件位置 3

#結果:

分析:

推薦學習:《PHP影片教學

以上是php載入檔案的方法有哪些的詳細內容。更多資訊請關注PHP中文網其他相關文章!

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