PHP中include()與require()的區別有哪些

來源:互聯網
上載者:User
  1. if($something){
  2. include("somefile");
  3. }
複製代碼

但不管$something取何值,下面的代碼將把檔案somefile包含進檔案裡:

  1. if($something){
  2. require("somefile");
  3. }
複製代碼

下面的這個有趣的例子充分說明了這兩個函數之間的不同。

  1. $i = 1;
  2. while ($i < 3) {
  3. require("somefile.$i");
  4. $i++;
  5. }
複製代碼

在這段代碼中,每一次迴圈時,程式都將把同一個檔案包含進去。很顯然這不是程式員的初衷,從代碼中我們可以看出這段代碼希望在每次迴圈時,將不同的檔案包含進來。如果要完成這個功能,必須求助函數include():

  1. $i = 1;
  2. while ($i < 3) {
  3. include("somefile.$i");
  4. $i++;
  5. }
複製代碼

3,報錯方式例子,寫兩個php檔案,名字為test1.php 和test2.php,注意相同的目錄中,不要存在一個名字是test999.php的檔案。test.php

  1. include (”test999.php”);
  2. echo “abc”;
  3. ?>
複製代碼

test2.php

  1. require (”test999.php”)
  2. echo “abc”;
  3. ?>
複製代碼

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

瀏覽第二個檔案,因為沒有找到test999.php檔案,我們看到了報錯資訊,但是,報錯資訊的下邊沒有顯示abc,你看到的可能是類似下邊的情況:Warning: require(test1aaa.php) [function.require]: failed to open stream: No such file or directory in D:\WebSite\test.php on line 2Fatal error: require() [function.require]: Failed opening required ‘test1aaa.php’ (include_path=’.;C:\php5\pear’) in D:\WebSite\test.php on line 2

小結:include和require的區別:include引入檔案時,如果碰到錯誤,會給出提示,並繼續運行下邊的代碼。require引入檔案時,如果碰到錯誤,會給出提示,並停止運行下邊的代碼。

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.