首頁  >  文章  >  後端開發  >  使用include和require的區別實例分析

使用include和require的區別實例分析

怪我咯
怪我咯原創
2017-07-06 10:18:491040瀏覽

網路上太多關於PHP中includerequire區別。然而事實真的如此嗎,今天我們就透過一個具體的實例來簡單分析驗證下

先編輯command.php檔案

echo 'hello'.PHP_EOL;

然後編輯console.php檔案

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

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

Warning: require(command1.php): failed to open stream: No such file or directory in console.php on line 4

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

如果把require改為include

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

會報出這樣的錯誤:

Warning: include(command1.php): failed to open stream: No such file or directory in console.php on line 4

Warning: include(): Failed opening &#39;command1.php&#39; for inclusion (include_path=&#39;.&#39;) in console.php on line 4

Warning: include(command1.php): failed to open stream: No such file or directory in console.php on line 4

Warning: include(): Failed opening &#39;command1.php&#39; for inclusion (include_path=&#39;.&#39;) in console.php on line 4

Warning: include(command1.php): failed to open stream: No such file or directory in console.php on line 4

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

如果使用require_onceinclude_once,只要包含路徑正確,那麼循環#只執行一次。

總結:

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

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

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

以上是使用include和require的區別實例分析的詳細內容。更多資訊請關注PHP中文網其他相關文章!

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