Home  >  Article  >  Backend Development  >  PHP命名空间(namespace)的使用基础及示例_PHP

PHP命名空间(namespace)的使用基础及示例_PHP

WBOY
WBOYOriginal
2016-05-31 19:30:49879browse

PHP的命名空间(namespace)是PHP 5.3中加入最重要的一个新特性,这个概念在C#中已经很早就有了,php中的namespace其实和c#的概念是一样的。

一. PHP的命名空间主要解决三种冲突的问题:常量,函数,类

通俗理解:namespace就相当于是用来建一个目录,将namespace下面的代码放在该目录里面,与外面的区分开来。

/*
|---------------------------------
|namespace示例
|@黑眼诗人 <www.chenwei.ws>
|---------------------------------
*/
namespace myself;
function var_dump()
{
  echo 100;
}
var_dump();        //调用自定义函数(相对路径方式)
\myself\var_dump();    //调用自定义函数(绝对路径方式) 
\var_dump(100);     //调用全局的(系统的函数)

注意:namespace 之前不能有任何代码,除了declare();多个文件可以使用同一个命名空间,但同一命名空间下定义的内容是不能冲突的。namespace支持子命名空间,如:namespace \myself\good,相当于多级目录的概念。

二. 同一文件中存在多个命名空间的情况

1.

/**
 * 同一文件中若使用了多个命名空间,一般写法
 */
namespace nihao\shijie;
function demo()
{
  //.......
}
namespace hello\world;
function test()
{
  //........
}

\nihao\shijie\demo();
\hello\world\test();

2.

/**
 * 同一文件中若使用了多个命名空间,建议大括号扩起来
 */
namespace nihao\shijie{
  function test_one()
  {
  //......
  };
}
namespace hello\world{
  function test_two()
  {
  //........
  }
}
\nihao\shijie\test_one();
\hello\world\test_two();

同一文件内使用多个命名空间,主要用于项目将多个PHP脚本合并在同一文件中,实际中不提倡使用!

三. 名称解析规则(几个概念)

  1.非限定名称:名称中不包含命名空间分割符,如:myself

  2.限定名称:名称中含有命名空间分割符,如:nihao\shijie

  3.完全限定名称:名称中包含分割符,并以命名空间分割符开始,如:\nihao\shijie  (即绝对路径的概念)

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn