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

來源:互聯網
上載者:User

這幾天整理一份很亂的代碼,這才意識到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.

 

 

__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的位置,其他檔案包含這個共有檔案)。
特別是當你同一份代碼放多處時(例如一個測試環境和一個正式環境),你改檔案也不好改。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.