php include與require用法介紹

來源:互聯網
上載者:User

 require 的使用方法如 require("MyRequireFile.php"); 。這個函數通常放在 PHP 程式的最前面,PHP 程式在執行前,就會先讀入 require 所指定引入的檔案,使它變成 PHP 程式網頁的一部份。常用的函數,亦可以這個方法將它引入網頁中。

 

include()與require()的功能也基本相同(包含),但在用法上也有一些不同,include()是有條件包含函數,而require()則是無條件包含函數。例如在下面代碼中,如果變數$a為真,則將包含檔案a.php:

 代碼如下 複製代碼

if($a){
include("a.php");
}


include 使用方法如 include("MyIncludeFile.php"); 。這個函數一般是放在流程式控制制的處理部分中。PHP 程式網頁在讀到 include 的檔案時,才將它讀進來。這種方式,可以把程式執行時的流程簡單化。

 

而require()則和include()不同,不管$a取何值,下面的代碼將把檔案a.php包含進檔案裡:

 代碼如下 複製代碼

if($a){
require("a.php");
}

在錯誤處理方面,使用include語句,如果發生包含錯誤,程式將跳過include語句,雖然會顯示錯誤資訊但是程式還是會繼續執行!但requre卻會給你來個致命錯誤。

報錯

 

用例子來說話,寫兩個php檔案,名字為test1.php  和test2.php,注意相同的目錄中,不要存在一個名字是test999.php的檔案。

 代碼如下 複製代碼

test.php
<?PHP
include  (”test999.php”);
echo  “abc”;
?>

test2.php
<?PHP
require (”test999.php”)
echo  “abc”;
?>

瀏覽第一個檔案,因為沒有找到test999.php檔案,我們看到了報錯資訊,同時,報錯資訊的下邊顯示了abc,你看到的可能是類似下邊的情況:
Warning: include(test1aaa.php) [function.include]: failed to open stream: No such file or directory in D:WebSitetest.php on line 2

Warning: include() [function.include]: Failed opening ‘test1aaa.php’ for inclusion (include_path=’.;C:php5pear’) in D:WebSitetest.php on line 2
abc

瀏覽第二個檔案,因為沒有找到test999.php檔案,我們看到了報錯資訊,但是,報錯資訊的下邊沒有顯示abc,你看到的可能是類似下邊的情況:
Warning: require(test1aaa.php) [function.require]: failed to open stream: No such file or directory in D:WebSitetest.php on line 2

Fatal error: require() [function.require]: Failed opening required ‘test1aaa.php’ (include_path=’.;C:php5pear’) in D:WebSitetest.php on line 2

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.