很多开源系统如osCommerce框架中,都会在其源码中找到use这个关键字,如osCommerce框架中就在index.php文件中出现了这段源码:
?
|
1
2
|
use osCommerce\\OM\\Core\\Autoloader;
use osCommerce\\OM\\Core\\OSCOM;
|
其实,php的use关键字是自php5.3以上版本引入的。它的作用是给一个外部引用起别名。这是命名空间的一个重要特性,它同基于unix的文件系统的为文件或目录创建连接标志相类似。
PHP命名空间支持三种别名方式(或者说引用):
1、为一个类取别名
2、为一个接口取别名
3、为一个命名空间取别名
这三种方式都是用 use 关键字来完成。下面是三种别名的分别举例:
//Example #1 importing/aliasing with the use operator
?
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
<?php
namespacefoo;
useMy\\Full\\ClassnameasAnother;
//thisisthesameasuseMy\\Full\\NSnameasNSname
useMy\\Full\\NSname;
//importingaglobalclass
useArrayObject;
$obj=newnamespace\\Another;//instantiatesobjectofclassfoo\\Another
$obj=newAnother;//instantiatesobjectofclassMy\\Full\\Classname
NSname\\subns\\func();//callsfunctionMy\\Full\\NSname\\subns\\func
$a=newArrayObject(array(1));//instantiatesobjectofclassArrayObject
//withoutthe"useArrayObject"wewouldinstantiateanobjectofclassfoo\\ArrayObject
?>
|
注意的一点是,对于已命名的名字,全称就包含了分隔符,比如 Foo\\Bar,而不能用FooBar,而“\\Foo\\Bar”这个头部的"\\"是没必要的,也不建议这样写。引入名必须是全称,并且跟当前命名空间没有程序上的关联。
PHP也可以在同一行上申明多个,等同于上面的写法
?
|
1
2
3
4
5
6
|
<?php
useMy\\Full\\ClassnameasAnother,My\\Full\\NSname;
$obj=newAnother;//instantiatesobjectofclassMy\\Full\\Classname
NSname\\subns\\func();//callsfunctionMy\\Full\\NSname\\subns\\func
?>
|
还有值得一说的是,引入是在编译时执行的,因此,别名不会影响动态类,例如:
?
|
1
2
3
4
5
6
7
|
<?php
useMy\\Full\\ClassnameasAnother,My\\Full\\NSname;
$obj=newAnother;//instantiatesobjectofclassMy\\Full\\Classname
$a = 'Another';
$obj = New $a; // instantiates object of class Another
?>
|
相关文章
猜你喜欢
- ASP.NET自助建站系统中的用户注册和登录功能定制方法 2025-06-10
- ASP.NET自助建站系统的域名绑定与解析教程 2025-06-10
- 个人服务器网站搭建:如何选择合适的服务器提供商? 2025-06-10
- ASP.NET自助建站系统中如何实现多语言支持? 2025-06-10
- 64M VPS建站:如何选择最适合的网站建设平台? 2025-06-10
TA的动态
- 2025-07-10 怎样使用阿里云的安全工具进行服务器漏洞扫描和修复?
- 2025-07-10 怎样使用命令行工具优化Linux云服务器的Ping性能?
- 2025-07-10 怎样使用Xshell连接华为云服务器,实现高效远程管理?
- 2025-07-10 怎样利用云服务器D盘搭建稳定、高效的网站托管环境?
- 2025-07-10 怎样使用阿里云的安全组功能来增强服务器防火墙的安全性?
快网idc优惠网
QQ交流群
您的支持,是我们最大的动力!
热门文章
-
2025-05-29 79
-
2025-05-29 74
-
租用美国服务器有哪些要注意的事项(租用美国服务器有哪些要注意的事项)
2025-05-25 24 -
浅谈ASP.NET Core中间件实现分布式 Session
2025-05-29 107 -
2025-05-25 60
热门评论

