PHP6 Namespace
PHP6 的 snapshot 版本中,namespace 功能已经实现了,下面我们就通过几个简单的示例来介绍一下,如何在 PHP6 中使用 namespace。
一、如何定义 namespace?
namespace net::phpvim::code;
class Shape{
}
function draw() {
return "draw() in Shape.php\n";
}
function getCurrentNS() {
return __NAMESPACE__;
}
/* vim: set expandtab tabstop=4 shiftwidth=4: */
所有的类和函数名称会自动加上 namespace 名称作为前缀,相同的 namespace 也可以在多个 PHP 文件中被定义。
比如上面的代码中,完整的类名和函数名是:
net::phpvim::code::Shape
net::phpvim::code::draw()
二、如何使用呢?
require_once 'net/phpvim/code/Shape.php';
import net::phpvim::code;
import net::phpvim::code::Shape;
import net::phpvim::code::Shape as CPC_Shape;
// Create an instance object for Shape class
$shape0 = new net::phpvim::code::Shape();
$shape1 = new code::Shape();
$shape2 = new Shape();
$shape3 = new CPC_Shape();
// output: draw() in Shape.php
print net::phpvim::code::draw();
print code::draw();
// output: net::phpvim::code
print code::getCurrentNS();
/* vim: set expandtab tabstop=4 shiftwidth=4: */
import 指令
import 可以将任意的 package(这里借用一下 Java 的概念)导入到当前 scope 中来。
import 不可以使用在函数或者类中。
import 生效范围为当前定义位置到所在文件的结尾。
import 可以通过 AS 关键字定义别名。
import A::B; 等同于 import A::B as B。
三、其它
特殊的 empty namespace ::
echo ::draw();
/* vim: set expandtab tabstop=4 shiftwidth=4: */
:: 是一个特殊的 namespace,以 :: 开头的调用,将会在 global 范围查找并绑定相应的 Class 或者 Function。换句话说,定义在任意 namespace 中的 draw() 函数都不会被调用,而是调用 global 范围内的 draw() 函数。
constant __NAMESPACE__
__NAMESPACE__ 表示当前的 namespace 的名称。



姜运涛 said,
Wrote on July 23, 2007 @ 9:30 am
这样的 Namespace 给人的感觉怪怪的
shenzhe said,
Wrote on August 2, 2007 @ 3:28 pm
是怪怪的。。
:: 太多了