PHP的命名空間(namespace)是php5.3之后才有的之前學(xué)習(xí)php所以沒有這個東西了,最近用到了php命名空間了,下面我們一起來看看命名空間namespace用法
現(xiàn)在說這個,感覺有點過時了,但是感覺用namespace的人還是不多,估計還是因為不習(xí)慣吧。
class把一個一個function組織起來,namespace可以理解成把一個一個class,function等有序的組織起來。個人覺得,namespace的主要優(yōu)勢有
第一,可以更好的管理代碼
第二,文件一多,可以避免class,function的重名
第三,代碼可讀性增強了
1,定義namespace
- namespace userCenter;
- //php代碼
- namespace userCenter/register;
- //php代碼
- namespace userCenter/login {
- //php代碼
- }
命名空間不能嵌套或在同一代碼處聲明多次(只有最后一次會被識別),但是,你能在同一個文件中定義多個命名空間化的代碼,比較合適的做法是每個文件定義一個命名空間,可以是相同命名空間.
2,調(diào)用namespace
- /userCenter/register; //絕對調(diào)用
- userCenter/login; //相對調(diào)用
- use userCenter/register; //引用空間
- use userCenter/register as reg; //引用空間并加別名
3,實例說明,login.class.php
- <?php
- namespace userCenter;
- function check_username(){
- echo "login OK<br>";
- }
- class login{
- public function save(){
- echo "login had saved<br>";
- }
- }
- ?>
regist.class.php
- <?php
- namespace userCenter/regist
- {
- function check_username() {
- echo "regist OK<br>";
- }
- class regist{
- public function save(){
- echo "regist had saved<br>";
- }
- }
- }
- ?>
test.php
- <?php
- require "login.class.php";
- require "regist.class.php";
- use userCenter/regist; //使用use調(diào)用空間
- use userCenter/regist as reg; //as定義別名
- echo /userCenter/check_username(); //絕對調(diào)用
- $login = new /userCenter/login();
- echo $login->save();
- //Vevb.com
- echo regist/check_username(); //相對調(diào)用
- echo reg/check_username(); //別名調(diào)用
- $regist = new reg/regist();
- echo $regist->save();
使用use,比絕對調(diào)用要好一點,好比給class,function等加了一個前綴,這樣看起來就比較清楚了.
新聞熱點
疑難解答