PHP中include路徑的解決方法匯總


這幾天整理一份很亂的代碼,這才意識到php對include處理不是一般的賤:別的編程語言在處理include中的相對目錄時,都是以當前處理的文件作為基准。也就是說,如果A包含B,B包含C時,C再包含一個含相對路徑的文件,那么路徑是相對於C的。這樣的處理很自然,符合人們的直覺,也便於開發出路徑無關的程序包。

可是PHP不這樣,它優先相對工作目錄來處理,並且如果路徑中包含. ..的話,則只相對於工作目錄。
也許PHP這樣處理有它的理由,有誰知道的不妨告訴我。

下面是解決這一問題的幾種方式:

  • __FILE__   返回的是一個物理的真實路徑

__FILE__  always equals to the real path of a php script  regardless whether it's included.

  

 

  • $_SERVER['DOCUMENT_ROOT']     返回網站根目錄,跟網站配置文件的 DOCUMENTROOT的值一致.

This method allows you to specify a path relative to the web server doc_root for file inclusion. 
這也是許多項目在采用的一種不錯的方式,就我看來,缺點是,整個項目不方便移動。

例如你一開始放置在xxx.com/,后來需要放到xxx.com/abc/下的話,你要改文件(在一個公有文件中計算ROOT的位置,其他文件包含這個共有文件)。
特別是當你同一份代碼放多處時(例如一個測試環境和一個正式環境),你改文件也不好改。

  • chdir()

這種方式感覺稍嫌麻煩了點,隨時要記得恢復工作目錄也不是容易的事。寫完這句話后,我隨后寫了幾個測試文件,發現這種方式的最重要缺點不在麻煩,

而在它的副作用:改變了工作目錄,這會導致程序邏輯出錯。

 

  • set_include_path()

This way is the most convenient way but it's not without flaws. First, not in all cases you have permission to change server configuration. Second, if there are many path specified in include_path, the actually included file may not be the one you expected because there may be files of the same name under different directories. 
這是最方便的方式,但不是沒有缺點。首先,有時候你不見得有權限修改配置。其次,當不同路徑下的文件名有重復的時候,你會被搞糊塗的(就算你不會,你的維護者呢)。

  • auto_prepend_file and auto_append_file in php.ini

This almost the best way if your scripts commonly need a startup script. We can do a lot of useful things in the startup script, for examples, define constants, load configurations. But it's not always OK to change the php.ini settings. Remember the most adaptive application should be as independent from configs as possible.  
如果你每個腳本都需要包含一個通用腳本的話,這幾乎是最好的方式,但是,缺點還是,與配置相關,不夠獨立。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM