今天用的set_include_path和get_include_path,剛開始有些困惑,總結查詢到的資料,得到如下結論:
1. get_include_path
該函數用於擷取當前include_path 的值。
string get_include_path ( void )
例如windos下使用XAMPP輸出:.;D:\xampp\php\PEAR
2.
set_include_path
set_include_path()函數在指令碼裡動態地對PHP.ini中include_path修改。
include_path可以針對include和require的路徑範圍進行限定(預定義)。
(1)若沒設定include_path值,則需要寫完全的路徑,但是這樣這樣會引入很多外部檔案
例如:
include('123/test1.php'); include('123/test2.php');
(2)若設定include_path值可用下面代碼代替。
set_include_path('123/'); include('test1.php'); include('test2.php');
因為,執行include或require時,會去include_path指定路徑尋找要引入檔案,雖然不知道效能是否最佳化,但可以節省代碼。當然,還有玄機!
(3)這個函數不僅可定義一個檔案夾,還可定義很多檔案夾。如下,寫一個初始化函數:
function initialize(){ set_include_path(get_include_path().PATH_SEPARATOR . 'core/'); set_include_path(get_include_path().PATH_SEPARATOR . 'app/'); set_include_path(get_include_path().PATH_SEPARATOR . 'admin/'); set_include_path(get_include_path().PATH_SEPARATOR . 'lib/'); set_include_path(get_include_path().PATH_SEPARATOR . 'include/'); set_include_path(get_include_path().PATH_SEPARATOR.'data/'); set_include_path(get_include_path().PATH_SEPARATOR.'cache/');}
它的路徑成了:
.;C:\php5\pear;core/;app/;admin/;lib/;include/;data/;cache/
前面的.;C:\php5\pear;是php.ini中include_path的預設值。按照這個思路,如果載入許多檔案夾的話,就可以直接寫檔案名稱了。
同時設定多個include_path時可以用PHP常量PATH_SEPARATOR來分割。在類unix的系統中,PATH_SEPARATOR是 ":";在windows系統中,PATH_SEPARATOR的值是";";
樣本:
set_include_path(implode(PATH_SEPARATOR, array( realpath(APPLICATION_PATH . '/../lib'), get_include_path(), )));
(4)當指定一個目錄為include_path時,但是當lib目錄下找不到所要求包含的檔案,而在當前頁面目錄下正好存在這個名稱的檔案時,則轉為包含目前的目錄下的該檔案。
樣本:
set_include_path('projectName/home/Action/lib');require('a.php');
(5)當指定了多個目錄為 include_path ,而所要求包含的檔案在這幾個目錄都有相同名稱的檔案存在時,php選擇使用設定 include_path 時排位居前的目錄下的檔案。