php命名空间 namespace

来源:互联网 发布:firefox调用java 编辑:程序博客网 时间:2024/05/05 15:32
php命名空间 namespace




官方说法是:
在PHP中,命名空间用来解决在编写类库或应用程序时创建可重用的代码如类或函数时碰到的两类问题
1.用户编写的代码与PHP内部的类/函数/常量或第三方类/函数/常量之间的名字冲突。
2.为很长的标识符名称(通常是为了缓解第一类问题而定义的)创建一个别名(或简短)的名称,提高源代码的可读性。
其实命名空间就是为了解决引入不同的文件存在了两个相同的类的情况,其中 __NAMESPACE__  可以获取namespace的名称。
例如,我有一个index文件引入 test.php 和 test2.php.但是这两个文件中都含有 class take ,这样我们在index.php文件中
去实例化 new take就会报错的,这时候我们就需要使用命名空间。


test.php


<?php
namespace takes;
class take {
function __construct() {
print "this is test file! name is : ". __NAMESPACE__;
}
}


test2.php


<?php
namespace my;
class take {
function __construct() {
print "this is a my files! not test,name is : ". __NAMESPACE__;
}
}


index.php


use takes as a; //这样将test文件中的take类的命名空间取别名 为a(纯粹练习用的);
require_once('test.php');
require_once('test2.php');


$obj = new a\take(); //test文件中的take类
print "<hr />";
$obj2 = new my\take(); //test2文件中的take类


输出结果为




this is test file! name is : takes
————————————————————————————————————————————————
this is a my files! not test,name is : my
0 0
原创粉丝点击