本文實例講述了php中namespace use用法。分享給大家供大家參考,具體如下:
現在說這個感覺有點過時了,但是感覺用namespace的人還是不多,估計還是因為不習慣吧。
class把一個一個function組織起來,namespace可以理解成把一個一個class,function等有序的組織起來。個人覺得,namespace的主要優勢有
第一,可以更好的管理代碼
第二,文件一多,可以避免class,function的重名
第三,代碼可讀性增強了
1. 定義namespace
namespace userCenter;//php代碼namespace userCenter/register;//php代碼namespace userCenter/login { //php代碼}
命名空間不能嵌套或在同一代碼處聲明多次(只有最后一次會被識別)。但是,你能在同一個文件中定義多個命名空間化的代碼,比較合適的做法是每個文件定義一個命名空間(可以是相同命名空間)。
2. 調用namespace
/userCenter/register; //絕對調用userCenter/login; //相對調用use userCenter/register; //引用空間use userCenter/register as reg; //引用空間并加別名
3. 實例說明
login.class.php
<?phpnamespace userCenter;function check_username(){ echo "login OK<br>";}class login{ public function save(){ echo "login had saved<br>"; }}?>
regist.class.php
<?phpnamespace userCenter/regist{ function check_username() { echo "regist OK<br>"; } class regist{ public function save(){ echo "regist had saved<br>"; } }}?>
test.php
<?phprequire "login.class.php";require "regist.class.php";use userCenter/regist; //使用use調用空間use userCenter/regist as reg; //as定義別名echo /userCenter/check_username(); //絕對調用$login = new /userCenter/login();echo $login->save();echo regist/check_username(); //相對調用echo reg/check_username(); //別名調用$regist = new reg/regist();echo $regist->save();
使用use,比絕對調用要好一點,好比給class,function等加了一個前綴,這樣看起來就比較清楚了。
希望本文所述對大家PHP程序設計有所幫助。