php中namespace use用法例子分析
class把一個一個function組織起來,namespace可以理解成把一個一個class,function等有序的'組織起來。個人覺得,namespace的主要優勢有
第一,可以更好的管理程式碼
第二,檔案一多,可以避免class,function的重名
第三,程式碼可讀性增強了
1. 定義namespace
namespace userCenter;//php程式碼namespace userCenterregister;//php程式碼namespace userCenterlogin { //php程式碼}
名稱空間不能巢狀或在同一程式碼處宣告多次(只有最後一次會被識別)。但是,你能在同一個檔案中定義多個名稱空間化的程式碼,比較合適的做法是每個檔案定義一個名稱空間(可以是相同名稱空間)。
2. 呼叫namespace
userCenterregister; //絕對呼叫userCenterlogin; //相對呼叫use userCenterregister; //引用空間use userCenterregister as reg; //引用空間並加別名
3. 例項說明
<"";require use="" usercenterregist="" as="" echo="" login="new" login-="">save();echo registcheck_username(); //相對呼叫echo regcheck_username(); //別名呼叫$regist = new regregist();echo $regist->save();
使用use,比絕對呼叫要好一點,好比給class,function等加了一個字首,這樣看起來就比較清楚了。