這幾天整理一份很亂的代碼,這才意識到php對include處理不是一般的賤:別的程式設計語言在處理include中的相對目錄時,都是以當前處理的檔案作為基準。也就是說,如果A包含B,B包含C時,C再包含一個含相對路徑的檔案,那麼路徑是相對於C的。這樣的處理很自然,符合人們的直覺,也便於開發出路徑無關的程式包。
可是PHP不這樣,它優先相對工作目錄來處理,並且如果路徑中包含. ..的話,則只相對於工作目錄。
也許PHP這樣處理有它的理由,有誰知道的不妨告訴我。
下面是解決這一問題的幾種方式:
__FILE__ always equals to the real path of a php script regardless whether it''s included.
__FILE__ helps you specify the file to include using relative path to the including file.
這種方法首選推薦。雖然你的include語句會因此要寫得長一些,但是一個字,值!
<?php 本文來自:http://www.87717.com
include dirname(__FILE__).''/subdir'';
//dirname return value does not contain the trailing slash
?>
- $_SERVER[''DOCUMENT_ROOT'']
This method allows you to specify a path relative to the web server doc_root for file inclusion.
這也是許多項目在採用的一種不錯的方式,就我看來,缺點是,整個項目不方便移動。
例如你一開始放置在xxx.com/,後來需要放到xxx.com/abc/下的話,你要改檔案(在一個公有檔案中計算ROOT的位置,其他檔案包含這個共有檔案)。
特別是當你同一份代碼放多處時(例如一個測試環境和一個正式環境),你改檔案也不好改。