php中的命名空间

时间:2012-06-25 06:01:00

标签: php-5.3

<?php
namespace foo;
use My\Full\Classname as Another;

// this is the same as use My\Full\NSname as NSname
use My\Full\NSname;

// importing a global class
use ArrayObject;

$obj = new namespace\Another; // instantiates object of class foo\Another
$obj = new Another; // instantiates object of class My\Full\Classname
NSname\subns\func(); // calls function My\Full\NSname\subns\func
$a = new ArrayObject(array(1)); // instantiates object of class ArrayObject
// without the "use ArrayObject" we would instantiate an object of class foo\ArrayObject
?> 

请帮助我。

use My\Full\Classname as Another;

的含义是什么?

1 个答案:

答案 0 :(得分:1)

这是一个别名。每当您将Another称为(相对)命名空间或类名时,它都会被解析为\My\Full\Classname

$x = new Another;
echo get_class($x); // "\My\Full\Classname"
$y = new Another\Something;
echo get_class($y); // "\My\Full\Classname\Something"

以命名空间分隔符\开头的标识符是完全限定名称。如果缺少标识符,则会针对当前名称空间和use定义的别名定义(按此顺序)解析标识符(usenamespace中的标识符除外):他们总是完全合格的。)

PHP-Manual: Namespaces