php中命名空間namespace用法介紹
現在說這個,感覺有點過時了,但是感覺用namespace的人還是不多,估計還是因為不習慣吧。
class把一個一個function組織起來,namespace可以理解成把一個一個class,function等有序的組織起來。個人覺得,namespace的主要優勢有
第一,可以更好的管理代碼
第二,檔案一多,可以避免class,function的重名
第三,代碼可讀性增強了
1,定義namespace
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 |
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
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61 |
namespace userCenter;
function check_username(){
echo "login OK
";
}
class login{
public function save(){
echo "login had saved
";
}
}
?>
regist.class.php
namespace userCenter\regist
{
function check_username() {
echo "regist OK
";
}
class regist{
public function save(){
echo "regist had saved
";
}
}
}
?>
|
test.php
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35 |
require "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等加了一個首碼,這樣看起來就比較清楚了
http://www.bkjia.com/PHPjc/1004541.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/1004541.htmlTechArticlephp中命名空間namespace用法介紹 現在說這個,感覺有點過時了,但是感覺用namespace的人還是不多,估計還是因為不習慣吧。 class把一個一個...