網路上太多關於PHP中include與require區別。然而事實真的如此嗎,今天我們就透過一個具體的實例來簡單分析驗證下
先編輯command.php檔案
1 | echo 'hello'.PHP_EOL;
|
登入後複製
然後編輯console.php檔案
1 2 3 | for ( $i =1; $i <=3;++ $i ){
require 'command1.php';
}
|
登入後複製
原本想要包含並執行這個echo,沒想到寫錯了檔名,如果是require,會報出這樣的錯誤:
1 2 3 4 5 | 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 'command1.php' (include_path='.') 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 'command1.php' (include_path='.') in console.php on line 4
|
登入後複製
如果把require改為include
1 2 3 | for ( $i =1; $i <=3;++ $i ){
include 'command1.php';
}
|
登入後複製
會報出這樣的錯誤:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | Warning: include (command1.php): failed to open stream: No such file or directory in console.php on line 4
Warning: include (): Failed opening 'command1.php' for inclusion (include_path='.') 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 'command1.php' for inclusion (include_path='.') 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 'command1.php' for inclusion (include_path='.') 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 'command1.php' for inclusion (include_path='.') 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 'command1.php' for inclusion (include_path='.') 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 'command1.php' for inclusion (include_path='.') in console.php on line 4
|
登入後複製
如果使用require_once或include_once,只要包含路徑正確,那麼循環#只執行一次。
總結:
使用require,如果檔案沒有包含成功,就會報出一個fatal error,整個程式就中止了。
使用include,如果檔案沒有包含成功,就會報出一個普通的warning,之後的程式碼仍會執行。
如果你的網路程式使用了MVC這種對檔案包含強依賴的設計方法,請使用require_once。
以上是使用include和require的區別實例分析的詳細內容。更多資訊請關注PHP中文網其他相關文章!