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
官方说法是:
在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
- php命名空间 namespace
- php namespace-命名空间
- PHP 命名空间(namespace)
- PHP namespace 命名空间
- php命名空间namespace
- PHP 命名空间 namespace
- php 命名空间namespace use
- php 命名空间namespace use
- [php] namespace命名空间解析
- [ 笔记 ] PHP 命名空间(namespace)
- php命名空间(namespace)
- php中的命名空间namespace
- PHP命名空间(Namespace)的使用详解
- PHP命名空间(Namespace)的使用详解
- php命名空间namespace使用笔记
- PHP命名空间(Namespace)的使用详解
- PHP命名空间(Namespace)的使用详解
- PHP命名空间(Namespace)简明教程
- HDU 3080 The plan of city rebuild(prim和kruskal)
- 函数的返回引用
- Android开发之使用Handler刷新UI控件
- View 处理的原则?
- View中getHitRect(Rect outRect)的作用?
- php命名空间 namespace
- 韩国票房:“蜘蛛侠”挤掉“美队”称王
- 如何addView时 , 设置framelayout的子View的位置
- android addView() 默认的params 是什么?
- 占位符的概念?
- cygwin 中 dll 路径
- uva 11987 Almost Union-Find(带删除操作的并查集)
- translateAnimation.setFillxxx()作用是什么?
- C/C++ int 高16位赋值,低16位赋值 //int 高16位取值,低16位取值