執行個體比較PHP中include和require的區別

來源:互聯網
上載者:User
網上太多關於PHP中include與require區別。然而事實真的如此嗎,今天我們就通過一個具體的執行個體來簡單分析驗證下

先編輯command.php檔案


echo 'hello'.PHP_EOL;

然後編輯console.php檔案


for($i=1;$i<=3;++$i){require 'command1.php';}

原本想要包含並執行這個echo,沒想到寫錯了檔案名稱,如果是require,會報出這樣的錯誤:


Warning: require(command1.php): failed to open stream: No such file or directory in console.php on line 4Fatal error: require(): Failed opening required 'command1.php' (include_path='.') in console.php on line 4PHP Warning: require(command1.php): failed to open stream: No such file or directory in console.php on line 4PHP Fatal error: require(): Failed opening required 'command1.php' (include_path='.') in console.php on line 4

如果把require改為include


for($i=1;$i<=3;++$i){include 'command1.php';}

會報出這樣的錯誤:


Warning: include(command1.php): failed to open stream: No such file or directory in console.php on line 4Warning: include(): Failed opening 'command1.php' for inclusion (include_path='.') in console.php on line 4Warning: include(command1.php): failed to open stream: No such file or directory in console.php on line 4Warning: include(): Failed opening 'command1.php' for inclusion (include_path='.') in console.php on line 4Warning: include(command1.php): failed to open stream: No such file or directory in console.php on line 4Warning: include(): Failed opening 'command1.php' for inclusion (include_path='.') in console.php on line 4PHP Warning: include(command1.php): failed to open stream: No such file or directory in console.php on line 4PHP Warning: include(): Failed opening 'command1.php' for inclusion (include_path='.') in console.php on line 4PHP Warning: include(command1.php): failed to open stream: No such file or directory in console.php on line 4PHP Warning: include(): Failed opening 'command1.php' for inclusion (include_path='.') in console.php on line 4PHP Warning: include(command1.php): failed to open stream: No such file or directory in console.php on line 4PHP Warning: include(): Failed opening 'command1.php' for inclusion (include_path='.') in console.php on line 4

如果使用require_once或者include_once,只要包含路徑正確,那麼迴圈只執行一次。

總結:

使用require,如果檔案沒有包含成功,就會報出一個fatal error,整個程式就中止了。

使用include,如果檔案沒有包含成功,就會報出一個普通的warning,之後的代碼仍會執行。

如果你的Web程式使用了MVC這種對檔案包含強依賴的設計方法,請使用require_once。

聯繫我們

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