PHP 的 require & include

發表於 | 8.28.2009 | 無回應

require() is identical to include() except upon failure it will produce a fatal E_ERROR level error.

In other words, it will halt the script whereas include() only emits a warning (E_WARNING)...
也就是說, 相對 include() 而言, require() 一旦有誤時, 程式會終止執行

which allows the script to continue.
而 include() 除了警語, 程式還是會跑完

#require() 的用法和 include() 一樣
#都是賦予一個檔案, 所以錯誤都是出現在找不到檔案
 

include "/path/to/file";
#這樣的寫法較標準, 雖然 include ("/path/to/file"); 也可以

#在迴圈內需要 include "/path/to/file"; 時
#而該 file 內如果定義有 user function 的話
#應該將 user function 移到迴圈外再引用
#或者另外將 user function 以檔案的方式在迴圈開始前 include()
#否則會在迴圈內重複宣告同樣一個 user function
 

Fatal errorCannot redeclare user_function() (previously declared) 
#這個 user_function 在迴圈內只會在第一次 include() 時使用, 然後因錯誤而終止執行