php中命名空間namespace用法介紹_PHP教程

來源:互聯網
上載者:User

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把一個一個...

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.