什么是命名空间?从广义上来说,命名空间是一种封装事物的方法。在很多地方都可以见到这种抽象概念。例如,在操作系统中目录用来将相关文件分组,对于目录中的文件来说,它就扮演了命名空间的角色。具体举个例子,文件 foo.txt 可以同时在目录/home/greg 和 /home/other 中存在,但在同一个目录中不能存在两个 foo.txt 文件。另外,在目录 /home/greg 外访问 foo.txt 文件时,我们必须将目录名以及目录分隔符放在文件名之前得到 /home/greg/foo.txt。这个原理应用到程序设计领域就是命名空间的概念。
在PHP中,命名空间用来解决在编写类库或应用程序时创建可重用的代码如类或函数时碰到的两类问题: In the PHP world, namespaces are designed to solve two problems that authors of libraries and applications encounter when creating re-usable code elements such as classes or functions:
PHP 命名空间提供了一种将相关的类、函数和常量组合到一起的途径。下面是一个说明 PHP 命名空间语法的示例:
Example #1 命名空间语法示例
<?php
namespace my\name; // 参考 "定义命名空间" 小节
class MyClass {}
function myfunction() {}
const MYCONST = 1;
$a = new MyClass;
$c = new \my\name\MyClass; // 参考 "全局空间" 小节
$a = strlen('hi'); // 参考 "使用命名空间:后备全局函数/常量" 小节
$d = namespace\MYCONST; // 参考 "namespace操作符和__NAMESPACE__常量” 小节
$d = __NAMESPACE__ . '\MYCONST';
echo constant($d); // 参考 "命名空间和动态语言特征" 小节
?>
PHP 在 5.3.0 以后的版本开始支持命名空间。
Anonymous (2011-07-14 04:14:19)
PHP Namespaces do not only provide a way in which to group related classes, functions and constants, but also a way in which to group related classes, interfaces, functions and constants.
Dmitry Snytkine (2011-05-31 06:54:58)
Just a note: namespace (even nested or sub-namespace) cannot be just a number, it must start with a letter.
For example, lets say you want to use namespace for versioning of your packages or versioning of your API:
namespace Mynamespace\1; // Illegal
Instead use this:
namespace Mynamespace\v1; // OK
SteveWa (2011-02-27 08:45:41)
Thought this might help other newbies like me...
Name collisions means:
you create a function named db_connect, and somebody elses code that you use in your file (i.e. an include) has the same function with the same name.
To get around that problem, you rename your function SteveWa_db_connect which makes your code longer and harder to read.
Now you can use namespaces to keep your function name separate from anyone else's function name, and you won't have to make extra_long_named functions to get around the name collision problem.
So a namespace is like a pointer to a file path where you can find the source of the function you are working with