首頁  >  文章  >  後端開發  >  php命名空间 namespace_PHP教程

php命名空间 namespace_PHP教程

WBOY
WBOY原創
2016-07-13 10:31:32687瀏覽

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.用...
陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn