什么是命名空间?借用官方文档的一段话:
从广义上来说,命名空间是一种封装事物的方法。在很多地方都可以见到这种抽象概念。例如,在操作系统中目录用来将相关文件分组,对于目录中的文件来说,它就扮演了命名空间的角色。具体举个例子,文件 foo.txt 可以同时在目录/home/greg 和 /home/other 中存在,但在同一个目录中不能存在两个 foo.txt 文件。另外,在目录 /home/greg 外访问 foo.txt 文件时,我们必须将目录名以及目录分隔符放在文件名之前得到 /home/greg/foo.txt。这个原理应用到程序设计领域就是命名空间的概念。
在PHP中,命名空间用来解决在编写类库或应用程序时创建可重用的代码如类或函数时碰到的两类问题:
用户编写的代码与PHP内部的类/函数/常量或第三方类/函数/常量之间的名字冲突。
为很长的标识符名称(通常是为了缓解第一类问题而定义的)创建一个别名(或简短)的名称,提高源代码的可读性。
我的项目目录如下所示:
在index.php需要同时使用space/Tree.php和time/Tree.php这两个文件,如果直接将这个两个文件引用进来的话因为文件名都一样,所以会出错,怎么办呢,现在就需要命名空间了。
space/Tree.php
<?php
namespace Time;
echo '<BR>Time';
class Tree
{
public function leaves($value='')
{
echo '<BR>Time leaves';
}
}//end class
time/Tree.php
<?php
namespace Space;
echo '<BR>Space';
class Tree
{
public function leaves($value='')
{
echo '<BR>Space leaves';
}
}//end class
index.php
<?php
namespace socket;
spl_autoload_register(function ($class) {
if ($class) {
$file = str_replace('\\', '/', $class);
$file .= '.php';
if (file_exists($file)) {
include "$file";
}
}
});
$tree = new \Space\Tree(); //这是使用的space/Tree.php中的类Tree
$tree->leaves();
$trees = new \Time\Tree(); //这是使用的time/Tree.php中的类Tree
$trees->leaves();
输出结果如图:
Author:leedaning
本文地址:http://blog.csdn.net/leedaning/article/details/51322878