欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

php命名空间 namespace_PHP教程

程序员文章站 2024-02-07 19:29:46
...
php命名空间 namespace




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


test.php


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


test2.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 "
";
$obj2 = new my\take(); //test2文件中的take类


输出结果为




this is test file! name is : takes
————————————————————————————————————————————————
this is a my files! not test,name is : my

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/762933.htmlTechArticlephp命名空间 namespace 官方说法是: 在PHP中,命名空间用来解决在编写类库或应用程序时创建可重用的代码如类或函数时碰到的两类问题 1.用...
相关标签: 空间