php文件包含的幾種方式總結(jié)
四種語句
PHP中有四個加載文件的語句:include、require、include_once、require_once。
基本語法
require:require函數(shù)一般放在PHP腳本的最前面,PHP執(zhí)行前就會先讀入require指定引入的文件,包含并嘗試執(zhí)行引入的腳本文件。require的工作方式是提高PHP的執(zhí)行效率,當它在同一個網(wǎng)頁中解釋過一次后,第二次便不會解釋。但同樣的,正因為它不會重復解釋引入文件,所以當PHP中使用循環(huán)或條件語句來引入文件時,需要用到include。
include:可以放在PHP腳本的任意位置,一般放在流程控制的處理部分中。當PHP腳本執(zhí)行到include指定引入的文件時,才將它包含并嘗試執(zhí)行。這種方式可以把程序執(zhí)行時的流程進行簡單化。當?shù)诙斡龅较嗤募r,PHP還是會重新解釋一次,include相對于require的執(zhí)行效率下降很多,同時在引入文件中包含用戶自定義函數(shù)時,PHP在解釋過程中會發(fā)生函數(shù)重復定義問題。
require_once / include_once:分別與require / include作用相同,不同的是他們在執(zhí)行到時會先檢查目標內(nèi)容是不是在之前已經(jīng)導入過,如果導入過了,那么便不會再次重復引入其同樣的內(nèi)容。
相互區(qū)別
include和require:
include有返回值,而require沒有返回值。
include在加載文件失敗時,會生成一個警告(E_WARNING),在錯誤發(fā)生后腳本繼續(xù)執(zhí)行。所以include用在希望繼續(xù)執(zhí)行并向用戶輸出結(jié)果時。
//test1.php <?php include './tsest.php'; echo 'this is test1'; ?> //test2.php <?php echo 'this is test2\n'; function test() { echo 'this is test\n'; } ?> //結(jié)果: this is test1
require在加載失敗時會生成一個致命錯誤(E_COMPILE_ERROR),在錯誤發(fā)生后腳本停止執(zhí)行。一般用在后續(xù)代碼依賴于載入的文件的時候。
//test1.php <?php require './tsest.php'; echo 'this is test1'; ?> //test2.php <?php echo 'this is test2\n'; function test() { echo 'this is test\n'; } ?>
結(jié)果:
include和include_once:
include載入的文件不會判斷是否重復,只要有include語句,就會載入一次(即使可能出現(xiàn)重復載入)。而include_once載入文件時會有內(nèi)部判斷機制判斷前面代碼是否已經(jīng)載入過。這里需要注意的是include_once是根據(jù)前面有無引入相同路徑的文件為判斷的,而不是根據(jù)文件中的內(nèi)容(即兩個待引入的文件內(nèi)容相同,使用include_once還是會引入兩個)。
//test1.php <?php include './test2.php'; echo 'this is test1'; include './test2.php'; ?> //test2.php <?php echo 'this is test2'; ?> //結(jié)果: this is test2this is test1this is test2 //test1.php <?php include './test2.php'; echo 'this is test1'; include_once './test2.php'; ?> //test2.php <?php echo 'this is test2'; ?> //結(jié)果: this is test2this is test1 //test1.php <?php include_once './test2.php'; echo 'this is test1'; include './test2.php'; ?> //test2.php <?php echo 'this is test2'; ?> //結(jié)果: this is test2this is test1this is test2 //test1.php <?php include_once './test2.php'; echo 'this is test1'; include_once './test2.php'; ?> //test2.php <?php echo 'this is test2'; ?> //結(jié)果: this is test2this is test1
require和require_once:同include和include_once的區(qū)別相同。
以上就是本次介紹的全部知識點內(nèi)容,感謝大家對腳本之家的支持。
相關(guān)文章
重新封裝zend_soap實現(xiàn)http連接安全認證的php代碼
重新封裝zend_soap實現(xiàn)http連接安全認證,需要的朋友可以參考下。2011-01-01PHP常用開發(fā)函數(shù)解析之數(shù)組篇[未完結(jié)]
數(shù)組處理函數(shù)在PHP開發(fā)中非常常見,學習好數(shù)組處理函數(shù)至關(guān)重要.數(shù)組處理函數(shù)在實際應用中涉及到:數(shù)組的創(chuàng)建,字符串于數(shù)組的相互轉(zhuǎn)換,數(shù)組轉(zhuǎn)XML,數(shù)組轉(zhuǎn)JSON.數(shù)組的檢測.數(shù)組的合并于分割.數(shù)組的數(shù)目.獲取數(shù)組中的所有值,獲取數(shù)組中的所有鍵值2012-07-07