PHP Portal » PHP Handbuch » Using namespaces: Aliasing/Importing

Werbung

Using namespaces: Aliasing/Importing


The ability to refer to an external fully qualified name with an alias, or importing, is an important feature of namespaces. This is similar to the ability of unix-based filesystems to create symbolic links to a file or to a directory.

PHP namespaces support two kinds of aliasing or importing: aliasing a class name, and aliasing a namespace name. Note that importing a function or constant is not supported.

In PHP, aliasing is accomplished with the use operator. Here is an example showing all 3 kinds of importing:

PHP Code
1
2
3
4
5
6
7
8
9
10
11
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

Note that for namespaced names (fully qualified namespace names containing namespace separator, such as Foo\Bar as opposed to global names that do not, such as FooBar), the leading backslash is unnecessary and not allowed, as import names must be fully qualified, and are not processed relative to the current namespace.

PHP additionally supports a convenience shortcut to place multiple use statements on the same line

PHP Code
1
2
3
use My\Full\Classname as Another, My\Full\NSname; $obj = new Another; // instantiates object of class My\Full\Classname NSname\subns\func(); // calls function My\Full\NSname\subns\func

Importing is performed at compile-time, and so does not affect dynamic class, function or constant names.

PHP Code
1
2
3
4
use My\Full\Classname as Another, My\Full\NSname; $obj = new Another; // instantiates object of class My\Full\Classname $a = 'Another'; $obj = new $a; // instantiates object of class Another

In addition, importing only affects unqualified and qualified names. Fully qualified names are absolute, and unaffected by imports.

PHP Code
1
2
3
4
5
use My\Full\Classname as Another, My\Full\NSname; $obj = new Another; // instantiates object of class My\Full\Classname $obj = new \Another; // instantiates object of class Another $obj = new Another\thing; // instantiates object of class My\Full\Classname\thing $obj = new \Another\thing; // instantiates object of class Another\thing