当前位置:首页 > PHP教程 > php应用 > 列表

PHP中的use关键字概述

发布:smiling 来源: PHP粉丝网  添加日期:2021-03-23 11:58:49 浏览: 评论:0 

这篇文章主要介绍了PHP中的use关键字,需要的朋友可以参考下

很多开源系统如osCommerce框架中,都会在其源码中找到use这个关键字,如osCommerce框架中就在index.php文件中出现了这段源码:

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. <?php 
  2. namespacefoo; 
  3. useMy\Full\ClassnameasAnother; 
  4.  
  5. //thisisthesameasuseMy\Full\NSnameasNSname 
  6. useMy\Full\NSname; 
  7.  
  8. //importingaglobalclass 
  9. useArrayObject; 
  10.  
  11. $obj=newnamespace\Another;//instantiatesobjectofclassfoo\Another 
  12. $obj=newAnother;//instantiatesobjectofclassMy\Full\Classname 
  13. NSname\subns\func();//callsfunctionMy\Full\NSname\subns\func 
  14. $a=newArrayObject(array(1));//instantiatesobjectofclassArrayObject 
  15. //withoutthe"useArrayObject"wewouldinstantiateanobjectofclassfoo\ArrayObject 
  16. ?> 

注意的一点是,对于已命名的名字,全称就包含了分隔符,比如 Foo\Bar,而不能用FooBar,而“\Foo\Bar”这个头部的"\"是没必要的,也不建议这样写。引入名必须是全称,并且跟当前命名空间没有程序上的关联。

PHP也可以在同一行上申明多个,等同于上面的写法

  1. <?php 
  2. useMy\Full\ClassnameasAnother,My\Full\NSname; 
  3.  
  4. $obj=newAnother;//instantiatesobjectofclassMy\Full\Classname 
  5. NSname\subns\func();//callsfunctionMy\Full\NSname\subns\func 
  6. ?> 

还有值得一说的是,引入是在编译时执行的,因此,别名不会影响动态类,例如:

  1. <?php 
  2. useMy\Full\ClassnameasAnother,My\Full\NSname; 
  3.  
  4. $obj=newAnother;//instantiatesobjectofclassMy\Full\Classname 
  5. $a = 'Another'
  6. $obj = New $a// instantiates object of class Another 
  7. ?> 

这里由于给变量$a 赋值了 'Another',编译的时候,就将$a 定位到 Classname 了。

更详细的用法读者可以查阅php手册或关注本站后续相关文章。

Tags: use关键字

分享到: