PHP中的use关键字概述

yipeiwu_com6年前PHP代码库

很多开源系统如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

<?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也可以在同一行上申明多个,等同于上面的写法

<?php
useMy\Full\ClassnameasAnother,My\Full\NSname;

$obj=newAnother;//instantiatesobjectofclassMy\Full\Classname
NSname\subns\func();//callsfunctionMy\Full\NSname\subns\func
?>

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

<?php
useMy\Full\ClassnameasAnother,My\Full\NSname;

$obj=newAnother;//instantiatesobjectofclassMy\Full\Classname
$a = 'Another';
$obj = New $a; // instantiates object of class Another
?>

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

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

相关文章

PHP4和PHP5性能测试和对比 测试代码与环境

作者:heiyeluren博客:http://blog.csdn.net/heiyeshuwu时间:2007年8月6日PHP 4到今年年底PHP Group将不再对其进行支持了,所以为了...

关于shopex同步ucenter的redirect问题,导致script不运行

首先此问题来自向这个帖子 http://hi.baidu.com/fire_love_live/item/247276cfda421217b67a24c7 需要说明的是,并非15处需要修...

PHP+JQuery+Ajax实现分页方法详解

PHP+JQuery+Ajax实现分页方法详解

本文实例讲述了PHP+JQuery+Ajax实现分页的方法。分享给大家供大家参考,具体如下: 为了锻炼下jQuery,决定自己动手写写分页 最终的效果如图: 点击某个字母后,下方显示以该...

joomla jce editor 解决上传中文名文件失败问题

不论是JCE还是CKEDITOR,都没解决中文名文件的问题,要么上传失败,要么传上去了中文名不能被web访问。相比之下,JCE更加人性化,比如文件上传后默认被选中,不需用户在那么小的弹出...

phpMyAdmin通过密码漏洞留后门文件

phpMyAdmin通过密码漏洞留后门文件

默认 phpMyAdmin:用户名 root 密码 root 或空登陆。 版本 2.11.3~2.11.4:用户名 'localhost'@'@" 登陆,无需密码。 版本...