首頁  >  文章  >  後端開發  >  php檔案包含的幾種方法

php檔案包含的幾種方法

爱喝马黛茶的安东尼
爱喝马黛茶的安东尼原創
2019-09-26 14:34:442537瀏覽

php檔案包含的幾種方法

四個語句

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作用相同,不同的是他們在執行到時會先檢查目標內容是不是在之前已經導入過,如果導入過了,那麼便不會再重複引入其同樣的內容。

相關推薦:《php教學

相互區別

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 
<?php 
require &#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;; 
} 
?>

結果:

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

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

以上是php檔案包含的幾種方法的詳細內容。更多資訊請關注PHP中文網其他相關文章!

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