发布于 2014-07-24 12:32:18 | 433 次阅读 | 评论: 0 | 来源: 网友投递

这里有新鲜出炉的PHP设计模式,程序狗速度看过来!

PHP开源脚本语言

PHP(外文名: Hypertext Preprocessor,中文名:“超文本预处理器”)是一种通用开源脚本语言。语法吸收了C语言、Java和Perl的特点,入门门槛较低,易于学习,使用广泛,主要适用于Web开发领域。PHP的文件后缀名为php。


本文介绍了php 5.3+的新关建字use及use关键字的用法和作用,感兴趣的同学看一下.

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

use osCommerceOMCoreAutoloader;
use osCommerceOMCoreOSCOM;

其实,php的use关键字是自php5.3以上版本引入的。它的作用是给一个外部引用起别名。这是命名空间的一个重要特性,它同基于unix的文件系统的为文件或目录创建连接标志相类似。

PHP命名空间支持三种别名方式(或者说引用):

1、为一个类取别名

2、为一个接口取别名

3、为一个命名空间取别名

这三种方式都是用 use 关键字来完成。下面是三种别名的分别举例:
//Example #1 importing/aliasing with the use operator

<?php
namespacefoo;
useMyFullClassnameasAnother;

//thisisthesameasuseMyFullNSnameasNSname
useMyFullNSname;

//importingaglobalclass
useArrayObject;

$obj=newnamespaceAnother;//instantiatesobjectofclassfooAnother
$obj=newAnother;//instantiatesobjectofclassMyFullClassname
NSnamesubnsfunc();//callsfunctionMyFullNSnamesubnsfunc
$a=newArrayObject(array(1));//instantiatesobjectofclassArrayObject
//withoutthe"useArrayObject"wewouldinstantiateanobjectofclassfooArrayObject
?>

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

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

<?php
useMyFullClassnameasAnother,MyFullNSname;

$obj=newAnother;//instantiatesobjectofclassMyFullClassname
NSnamesubnsfunc();//callsfunctionMyFullNSnamesubnsfunc
?>

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

<?php
useMyFullClassnameasAnother,MyFullNSname;

$obj=newAnother;//instantiatesobjectofclassMyFullClassname
$a = 'Another';
$obj = New $a; // instantiates object of class Another
?>

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

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



最新网友评论  共有(0)条评论 发布评论 返回顶部

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务