PHP命名空间

1、目的:为了解决重名问题,PHP函数名或类名不能相同。

2、解决方法:(1)约定前缀;功能名类似时,方法类名前加上模块名(2)使用命名空间。

3、命名空间的作用:命名空间将代码分出不同的空间(区域),每个空间的常量、函数、类的名字互不影响。

4、命名空间的使用:

(1)创建一个名为'Article'的命名空间

  <?php

    //创建一个名为'Article'的命名空间
    namespace Article;

  ?>

(2)类命名空间的语法调用  

  <?php

    namespace Article;

    class Comment { }

    namespace MessageBoard;

    class Comment { }

    //调用当前空间(MessageBoard)的Comment
    $comment = new Comment();

    //调用Article空间的Comment
    $article_comment = new \Article\Comment();

  ?>

(3)函数方法命名空间的语法调用

 

  <?php

 

    namespace Article;

 

    const PATH = '/article';

 

    function getCommentTotal() {
        return 100;
  }

 

  class Comment { }

 


  namespace MessageBoard;

 

  const PATH = '/message_board';

 

  function getCommentTotal() {
      return 300;
  }

 

  class Comment { }

 

  //调用当前空间的常量、函数和类
  echo PATH; ///message_board
  echo getCommentTotal(); //300
  $comment = new Comment();

 

  //调用Article空间的常量、函数和类
  echo \Article\PATH; ///article
  echo \Article\getCommentTotal(); //100
  $article_comment = new \Article\Comment();

 

?>

以上这些写法都类似于文件路径的语法: \空间名\元素名。

 

 

posted @ 2017-04-21 16:21  hooks  阅读(108)  评论(0编辑  收藏  举报